107 lines
3.9 KiB
Python
107 lines
3.9 KiB
Python
#!/usr/bin/env python3
|
||
"""Делает вход passwordless: TOTP первым, пароль — только если TOTP нет.
|
||
|
||
1. Политика «у пользователя есть TOTP».
|
||
2. MFA-validate: not_configured_action = skip.
|
||
3. Порядок: identification(10) → mfa(20) → password(30) с политикой skip.
|
||
4. login(100).
|
||
"""
|
||
import json
|
||
import urllib.error
|
||
import urllib.request
|
||
|
||
API = "http://192.168.1.114:9000/api/v3"
|
||
T = open("/root/.authentik-api-token").read().strip()
|
||
FLOW_NAME = "passwordless-2fa"
|
||
|
||
|
||
def call(method, path, body=None):
|
||
data = json.dumps(body).encode() if body is not None else None
|
||
req = urllib.request.Request(API + path, data=data, method=method,
|
||
headers={"Authorization": "Bearer " + T,
|
||
"Content-Type": "application/json"})
|
||
try:
|
||
with urllib.request.urlopen(req, timeout=30) as r:
|
||
raw = r.read()
|
||
return r.status, (json.loads(raw) if raw else {})
|
||
except urllib.error.HTTPError as e:
|
||
return e.code, e.read()[:400].decode("utf-8", "replace")
|
||
|
||
|
||
def get_or_create_policy():
|
||
st, d = call("GET", "/policies/expression/?page_size=100")
|
||
for p in (d.get("results", []) if st == 200 else []):
|
||
if p["name"] == "has-totp-device":
|
||
print("политика уже есть:", p["pk"])
|
||
return p["pk"]
|
||
expr = (
|
||
"try:\n"
|
||
" return request.user.device_set.filter(type='totp').exists()\n"
|
||
"except Exception:\n"
|
||
" return False\n"
|
||
)
|
||
st, p = call("POST", "/policies/expression/", {
|
||
"name": "has-totp-device",
|
||
"expression": expr,
|
||
"execution_logging": True,
|
||
})
|
||
if st not in (200, 201):
|
||
print("политика: ошибка", st, p)
|
||
return None
|
||
print("политика создана:", p["pk"])
|
||
return p["pk"]
|
||
|
||
|
||
def main():
|
||
flows = call("GET", "/flows/instances/?page_size=100")[1]["results"]
|
||
flow = next((f for f in flows if f["slug"] == "default-authentication-flow"), None)
|
||
if not flow:
|
||
print("flow не найден")
|
||
return
|
||
fpk = flow["pk"]
|
||
stages = {s["name"]: s["pk"] for s in
|
||
call("GET", "/stages/all/?page_size=100")[1]["results"]}
|
||
mfa_pk = stages["default-authentication-mfa-validation"]
|
||
pwd_pk = stages["default-authentication-password"]
|
||
login_pk = stages["default-authentication-login"]
|
||
ident_pk = stages["default-authentication-identification"]
|
||
|
||
pol = get_or_create_policy()
|
||
|
||
# MFA: если у пользователя нет устройства — пропустить
|
||
st, mfa = call("GET", f"/stages/authenticator/validate/{mfa_pk}/")
|
||
if st == 200:
|
||
call("PATCH", f"/stages/authenticator/validate/{mfa_pk}/",
|
||
{"not_configured_action": "skip"})
|
||
print("mfa: not_configured_action=skip")
|
||
|
||
# пересобираем bindings
|
||
st, bindings = call("GET", f"/flows/bindings/?target={fpk}&page_size=100")
|
||
for b in bindings.get("results", []):
|
||
call("DELETE", f"/flows/bindings/{b['pk']}/")
|
||
print("старые bindings удалены:", len(bindings.get("results", [])))
|
||
|
||
def bind(order, stage, policy=None):
|
||
body = {"target": fpk, "stage": stage, "order": order,
|
||
"evaluate_on_plan": False, "re_evaluate": True}
|
||
if policy:
|
||
body["policy"] = policy
|
||
st, r = call("POST", "/flows/bindings/", body)
|
||
print(f" bind {order} {stage[:8]}: {st}")
|
||
|
||
bind(10, ident_pk)
|
||
bind(20, mfa_pk)
|
||
bind(30, pwd_pk, pol)
|
||
bind(100, login_pk)
|
||
|
||
st, final = call("GET", f"/flows/bindings/?target={fpk}&page_size=100&ordering=order")
|
||
print()
|
||
print("итоговый порядок:")
|
||
for b in final.get("results", []):
|
||
print(f" {b['order']:>3} {b.get('stage_obj',{}).get('name')} "
|
||
f"policy={b.get('policy_obj')}")
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|