feat(members): split username/display_name, sync updates to authentik, add password reset API and refresh docs
This commit is contained in:
@@ -1,6 +1,8 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import secrets
|
||||
import string
|
||||
|
||||
import httpx
|
||||
from fastapi import HTTPException, status
|
||||
@@ -15,6 +17,12 @@ class AuthentikSyncResult:
|
||||
authentik_sub: str | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class AuthentikPasswordResetResult:
|
||||
user_id: int
|
||||
temporary_password: str
|
||||
|
||||
|
||||
class AuthentikAdminService:
|
||||
def __init__(self, settings: Settings) -> None:
|
||||
self.base_url = settings.authentik_base_url.rstrip("/")
|
||||
@@ -40,27 +48,76 @@ class AuthentikAdminService:
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _safe_username(sub: str, email: str) -> str:
|
||||
def _safe_username(sub: str | None, email: str) -> str:
|
||||
if email and "@" in email:
|
||||
return email.split("@", 1)[0]
|
||||
return sub.replace("|", "_")[:150]
|
||||
if sub:
|
||||
return sub.replace("|", "_")[:150]
|
||||
return "member-user"
|
||||
|
||||
def ensure_user(self, sub: str, email: str, display_name: str | None, is_active: bool = True) -> AuthentikSyncResult:
|
||||
@staticmethod
|
||||
def _generate_temporary_password(length: int = 14) -> str:
|
||||
alphabet = string.ascii_letters + string.digits + "!@#$%^&*"
|
||||
return "".join(secrets.choice(alphabet) for _ in range(length))
|
||||
|
||||
@staticmethod
|
||||
def _extract_first_result(data: dict) -> dict | None:
|
||||
results = data.get("results") if isinstance(data, dict) else None
|
||||
return results[0] if isinstance(results, list) and results else None
|
||||
|
||||
def _lookup_user_by_id(self, client: httpx.Client, user_id: int) -> dict | None:
|
||||
resp = client.get(f"/api/v3/core/users/{user_id}/")
|
||||
if resp.status_code == 404:
|
||||
return None
|
||||
if resp.status_code >= 400:
|
||||
raise HTTPException(status_code=502, detail="authentik_lookup_failed")
|
||||
return resp.json()
|
||||
|
||||
def _lookup_user_by_email_or_username(
|
||||
self, client: httpx.Client, *, email: str | None, username: str | None
|
||||
) -> dict | None:
|
||||
if email:
|
||||
resp = client.get("/api/v3/core/users/", params={"email": email})
|
||||
if resp.status_code >= 400:
|
||||
raise HTTPException(status_code=502, detail="authentik_lookup_failed")
|
||||
existing = self._extract_first_result(resp.json())
|
||||
if existing:
|
||||
return existing
|
||||
|
||||
if username:
|
||||
resp = client.get("/api/v3/core/users/", params={"username": username})
|
||||
if resp.status_code >= 400:
|
||||
raise HTTPException(status_code=502, detail="authentik_lookup_failed")
|
||||
existing = self._extract_first_result(resp.json())
|
||||
if existing:
|
||||
return existing
|
||||
|
||||
return None
|
||||
|
||||
def ensure_user(
|
||||
self,
|
||||
*,
|
||||
sub: str | None,
|
||||
email: str,
|
||||
username: str | None,
|
||||
display_name: str | None,
|
||||
is_active: bool = True,
|
||||
authentik_user_id: int | None = None,
|
||||
) -> AuthentikSyncResult:
|
||||
resolved_username = username or self._safe_username(sub=sub, email=email)
|
||||
payload = {
|
||||
"username": self._safe_username(sub=sub, email=email),
|
||||
"username": resolved_username,
|
||||
"name": display_name or email,
|
||||
"email": email,
|
||||
"is_active": is_active,
|
||||
}
|
||||
|
||||
with self._client() as client:
|
||||
resp = client.get("/api/v3/core/users/", params={"email": email})
|
||||
if resp.status_code >= 400:
|
||||
raise HTTPException(status_code=502, detail="authentik_lookup_failed")
|
||||
|
||||
data = resp.json()
|
||||
results = data.get("results") if isinstance(data, dict) else None
|
||||
existing = results[0] if isinstance(results, list) and results else None
|
||||
existing = None
|
||||
if authentik_user_id is not None:
|
||||
existing = self._lookup_user_by_id(client, authentik_user_id)
|
||||
if existing is None:
|
||||
existing = self._lookup_user_by_email_or_username(client, email=email, username=resolved_username)
|
||||
|
||||
if existing and existing.get("pk") is not None:
|
||||
user_pk = int(existing["pk"])
|
||||
@@ -78,3 +135,27 @@ class AuthentikAdminService:
|
||||
action="created",
|
||||
authentik_sub=created.get("uid"),
|
||||
)
|
||||
|
||||
def reset_password(
|
||||
self,
|
||||
*,
|
||||
authentik_user_id: int | None,
|
||||
email: str | None,
|
||||
username: str | None,
|
||||
) -> AuthentikPasswordResetResult:
|
||||
with self._client() as client:
|
||||
existing = None
|
||||
if authentik_user_id is not None:
|
||||
existing = self._lookup_user_by_id(client, authentik_user_id)
|
||||
if existing is None:
|
||||
existing = self._lookup_user_by_email_or_username(client, email=email, username=username)
|
||||
if not existing or existing.get("pk") is None:
|
||||
raise HTTPException(status_code=404, detail="authentik_user_not_found")
|
||||
|
||||
user_pk = int(existing["pk"])
|
||||
temp_password = self._generate_temporary_password()
|
||||
set_pwd_resp = client.post(f"/api/v3/core/users/{user_pk}/set_password/", json={"password": temp_password})
|
||||
if set_pwd_resp.status_code >= 400:
|
||||
raise HTTPException(status_code=502, detail="authentik_set_password_failed")
|
||||
|
||||
return AuthentikPasswordResetResult(user_id=user_pk, temporary_password=temp_password)
|
||||
|
||||
Reference in New Issue
Block a user