Files

54 lines
2.2 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""Привязывает политику через /policies/bindings/ с negate=true."""
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()
POLICY = "641a4b7d-56e6-420f-a7c8-d609a1f251cf"
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")
flows = call("GET", "/flows/instances/?page_size=100")[1]["results"]
fpk = next(f["pk"] for f in flows if f["slug"] == "default-authentication-flow")
st, bindings = call("GET", f"/flows/bindings/?target={fpk}&page_size=100&ordering=order")
pwd_binding = next(b for b in bindings["results"]
if b.get("stage_obj", {}).get("name") == "default-authentication-password")
print("binding пароля:", pwd_binding["pk"])
st, existing = call("GET", f"/policies/bindings/?target={pwd_binding['pk']}&page_size=10")
print("существующие policy bindings:", st, existing.get("pagination", {}).get("count")
if isinstance(existing, dict) else existing)
if isinstance(existing, dict) and existing.get("results"):
print("уже есть")
else:
st, r = call("POST", "/policies/bindings/", {
"policy": POLICY,
"target": pwd_binding["pk"],
"order": 0,
"enabled": True,
"negate": True,
"timeout": 30,
})
print("создание:", st, str(r)[:200])
st, final = call("GET", f"/policies/bindings/?target={pwd_binding['pk']}&page_size=10")
if isinstance(final, dict):
for b in final.get("results", []):
print(" policy binding:", b.get("policy_obj", {}).get("name"),
"negate=", b.get("negate"), "enabled=", b.get("enabled"))