from __future__ import annotations from dataclasses import dataclass import secrets import string import httpx from fastapi import HTTPException, status from app.core.config import Settings @dataclass class AuthentikSyncResult: user_id: int action: str user_sub: str | None = None @dataclass class AuthentikPasswordResetResult: user_id: int temporary_password: str @dataclass class AuthentikDeleteResult: action: str user_id: int | None = None class AuthentikAdminService: def __init__(self, settings: Settings) -> None: self.base_url = settings.authentik_base_url.rstrip("/") self.admin_token = settings.authentik_admin_token self.verify_tls = settings.authentik_verify_tls if not self.base_url or not self.admin_token: raise HTTPException( status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail="authentik_admin_not_configured", ) def _client(self) -> httpx.Client: return httpx.Client( base_url=self.base_url, headers={ "Authorization": f"Bearer {self.admin_token}", "Accept": "application/json", "Content-Type": "application/json", }, timeout=10, verify=self.verify_tls, ) @staticmethod def _safe_username(sub: str | None, email: str) -> str: if email and "@" in email: return email.split("@", 1)[0] if sub: return sub.replace("|", "_")[:150] return "member-user" @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, idp_user_id: int | None = None, ) -> AuthentikSyncResult: resolved_username = username or self._safe_username(sub=sub, email=email) payload = { "username": resolved_username, "name": display_name or email, "email": email, "is_active": is_active, } with self._client() as client: existing = None if idp_user_id is not None: existing = self._lookup_user_by_id(client, idp_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"]) patch_resp = client.patch(f"/api/v3/core/users/{user_pk}/", json=payload) if patch_resp.status_code >= 400: raise HTTPException(status_code=502, detail="authentik_update_failed") return AuthentikSyncResult(user_id=user_pk, action="updated", user_sub=existing.get("uid")) create_resp = client.post("/api/v3/core/users/", json=payload) if create_resp.status_code >= 400: raise HTTPException(status_code=502, detail="authentik_create_failed") created = create_resp.json() return AuthentikSyncResult( user_id=int(created["pk"]), action="created", user_sub=created.get("uid"), ) def reset_password( self, *, idp_user_id: int | None, email: str | None, username: str | None, ) -> AuthentikPasswordResetResult: with self._client() as client: existing = None if idp_user_id is not None: existing = self._lookup_user_by_id(client, idp_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) def delete_user( self, *, idp_user_id: int | None, email: str | None, username: str | None, ) -> AuthentikDeleteResult: with self._client() as client: existing = None if idp_user_id is not None: existing = self._lookup_user_by_id(client, idp_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: return AuthentikDeleteResult(action="not_found") user_pk = int(existing["pk"]) delete_resp = client.delete(f"/api/v3/core/users/{user_pk}/") if delete_resp.status_code in {204, 404}: return AuthentikDeleteResult( action="deleted" if delete_resp.status_code == 204 else "not_found", user_id=user_pk, ) if delete_resp.status_code >= 400: raise HTTPException(status_code=502, detail="authentik_delete_failed") return AuthentikDeleteResult(action="deleted", user_id=user_pk)