Files
shared/packages/python-backend/src/shared_backend/authproxy.py
T

831 lines
34 KiB
Python
Raw Normal View History

"""shared_backend.authproxy: the Python equivalent of shared/backend/auth's
Service/New/NewWithStore (Go) - the ONE shared AuthGuard-proxy engine for
every FastAPI-based project in this workspace that centralizes identity
through AuthGuard, instead of each project hand-rolling its own
status/setup/login/logout/TOTP/admin-user-CRUD proxy around AuthClient.
Extracted 2026-09-13 from three near-identical ~800-1000 line
implementations (Heretic, HordeWorker, InfiniteVideo), each explicitly
documented as mirroring the others and, ultimately, the reference Go
implementation (Original/GameStream/backend/cmd/gamestreamd/auth.go before
its own migration onto shared/backend/auth). Read any of those three
projects' pre-migration auth.py (or their own project's post-migration
git history) for the fuller narrative rationale behind each design choice
below - it is intentionally not repeated at length here.
Usage
-----
A project builds a `ProxyStore` implementation over whatever local
persistence it already has for two small, genuinely independent concerns:
a one-time "has this deployment's setup screen been completed" claim flag,
and (optionally) a "require login" toggle. It then calls `build_auth_router`
once, passing:
- `get_client(request) -> AuthClient | None`: resolve this request's
AuthClient from wherever the project stores it (typically
`request.app.state.auth_client`); `None` means AUTHGUARD_URL was unset
(auth-disabled mode - see `_LOCAL_PROFILE`'s doc comment below).
- `get_store(request) -> ProxyStore`: resolve this request's ProxyStore
the same way.
- `project_key`: this project's own lowercase identifier, passed to
`AuthClient(..., project_key=...)` by the project itself when
constructing its client - NOT re-passed here; this module never
constructs an AuthClient itself. Mentioned here only so a project
wiring this up remembers to set it.
- `legacy_cookie_name`: the project's own pre-migration session cookie
name, if any, cleared alongside AuthGuard's on logout for browsers that
still hold one.
- `secure_cookie`: whether cookies this router sets/clears should carry
the `Secure` attribute (mirror the project's own COOKIE_SECURE-style
setting).
and mounts the resulting `APIRouter` at `/api/auth` (the prefix every
existing consumer already uses - this module's own routes are declared
without a prefix, so a project could choose a different one, but doing so
would be a project-specific behavior change, not part of this migration).
Response shapes deliberately match shared/backend/auth (Go)'s: a nested
`user` object rather than flat fields, TOTP payloads nested under `data`,
etc. - the same standardization already applied when GameStream, OmniLogger,
and several other Go projects were migrated onto that engine. A project
adopting this module updates its own frontend to match; this is intentional,
not a bug.
"""
from __future__ import annotations
import abc
import os
from typing import Any, Callable, Optional
from fastapi import APIRouter, Depends, HTTPException, Request, Response
from pydantic import BaseModel
from .auth import MAX_PASSWORD_BYTES, ROLE_SUPERADMIN, can_manage_users, normalize_role
from .authclient import (
DEFAULT_COOKIE_NAME,
APIError,
AuthClient,
AuthClientError,
ManagedUser,
PublicUser,
forwarded_client_ip,
)
from .clientip import client_address, parse_trusted_proxies, trusted_proxies_from_env
from .ratelimit import AttemptLimiter
__all__ = ["ProxyStore", "build_auth_router"]
MIN_PASSWORD_LEN = 8
# Attempt limits for login and the TOTP verify/disable routes, the same numbers as the Go proxy
# (backend/auth/ratelimit.go): each key may make `limit` attempts per window.
ATTEMPT_WINDOW_SECONDS = 15 * 60
LOGIN_ACCOUNT_LIMIT = 10
LOGIN_CLIENT_LIMIT = 200
TOTP_ATTEMPT_LIMIT = 5
MAX_USERNAME_LEN = 64
MAX_EMAIL_LEN = 254
ERR_AUTH_REQUIRED = "Authentication required."
ERR_SETUP_COMPLETE = "Setup has already been completed."
ERR_INVALID_CREDENTIALS = "Invalid username or password."
ERR_INVALID_INPUT = "Invalid authentication input."
ERR_TOO_MANY_ATTEMPTS = "Too many attempts. Try again later."
ERR_SELF_SERVICE_PROFILE = (
"Self-service profile editing is only available to administrator accounts; "
"ask an administrator to update this account."
)
# Returned by handlers that need a real backing identity (not just an access
# gate) when AUTHGUARD_URL is unset; see _LOCAL_PROFILE's doc comment.
ERR_FEATURE_REQUIRES_AUTHGUARD = "This feature requires AUTHGUARD_URL to be configured."
# Raised whenever AuthGuard could not be reached or gave an unusable response
# - a real "invalid or expired session" always resolves to None instead,
# never this error - so every caller can safely report this same message
# rather than a generic "internal error" indistinguishable from any other bug.
ERR_AUTHGUARD_UNAVAILABLE = "Unable to reach the authentication service. Please try again shortly."
ERR_AUTHGUARD_NOT_CONFIGURED = "AUTHGUARD_URL is not configured, so sessions cannot be verified."
2026-09-15 23:26:02 +02:00
ERR_SECRET_NOT_SET = "SECRET environment variable is not set."
ERR_ADMIN_REQUIRED = "Administrator access required."
# _LOCAL_PROFILE is the fixed placeholder identity every handler reports when
# authentication is disabled, either because AUTHGUARD_URL is disabled or
# because ProjectConfigurator has turned off this project's login requirement.
# Role is superadmin so all application routes see the same Admin identity even
# though no credentials were supplied.
_LOCAL_PROFILE = PublicUser(
id=0, username="Admin", email="", role=ROLE_SUPERADMIN, totp_enabled=False
)
class ProxyStore(abc.ABC):
"""The small piece of local, project-owned persistence build_auth_router
needs beyond AuthGuard itself: the independent "require login" toggle
and the one-time "has this deployment's setup screen been completed"
claim flag. Mirrors Go's sharedauth.ProxyStore exactly (same five
operations); a project with no "require login" concept of its own can
make login_required always return True and set_login_required a no-op.
"""
@abc.abstractmethod
async def login_required(self) -> bool: ...
@abc.abstractmethod
async def set_login_required(self, required: bool) -> None: ...
@abc.abstractmethod
async def is_setup_claimed(self) -> bool: ...
@abc.abstractmethod
async def try_claim_setup(self) -> bool: ...
@abc.abstractmethod
async def unclaim_setup(self) -> None: ...
ClientGetter = Callable[[Request], Optional[AuthClient]]
StoreGetter = Callable[[Request], ProxyStore]
# Request/response models are declared at module level (not inside
# build_auth_router) deliberately: this file uses `from __future__ import
# annotations` (PEP 563), which turns every annotation into a string
# resolved later via the function's *module* globals - a class nested
# inside build_auth_router's local scope is invisible to that resolution,
# which silently breaks FastAPI's body-vs-query-param detection (a
# nested-class version of this router mistook every JSON body for a
# missing query parameter). Keeping these as plain module-level classes
# avoids that trap entirely.
class SetupRequest(BaseModel):
username: str
email: str
password: str
class LoginRequest(BaseModel):
identifier: Optional[str] = None
username: Optional[str] = None
email: Optional[str] = None
password: str
totpToken: str = ""
class UpdateMeRequest(BaseModel):
email: str = ""
username: str = ""
password: str = ""
class UpdateAccessRequest(BaseModel):
loginRequired: bool
class ManagedUserRequest(BaseModel):
username: str = ""
email: str = ""
password: str = ""
role: Optional[str] = None
class TotpTokenRequest(BaseModel):
token: str = ""
totpToken: str = ""
def _normalize_username(username: str) -> str:
username = (username or "").strip()
if not username or len(username) > MAX_USERNAME_LEN:
raise HTTPException(status_code=400, detail="Username is required.")
return username
def _normalize_email(email: str) -> str:
email = (email or "").strip().lower()
if not email or len(email) > MAX_EMAIL_LEN or email.count("@") != 1:
raise HTTPException(status_code=400, detail="Email is required and must be valid.")
local, domain = email.split("@", 1)
if not local or not domain or "." not in domain:
raise HTTPException(status_code=400, detail="Email is required and must be valid.")
return email
def _validate_password(password: str) -> None:
if len(password or "") < MIN_PASSWORD_LEN:
raise HTTPException(status_code=400, detail="Password must be at least 8 characters.")
# bcrypt reads only the first 72 bytes, so a longer password could not be stored faithfully.
if len(password.encode("utf-8")) > MAX_PASSWORD_BYTES:
raise HTTPException(
status_code=400, detail=f"Password must be at most {MAX_PASSWORD_BYTES} bytes."
)
def _raise_authguard_error(err: Exception, fallback: str) -> None:
"""Translates an authclient error into a FastAPI HTTPException. AuthGuard's
own httpapi handlers were built from this workspace's various original
local implementations, so their status codes and messages already match
closely - AuthGuard's APIError is forwarded close to verbatim rather than
re-mapped by hand. A non-APIError (a transport failure actually reaching
AuthGuard) falls back to a generic 500 with `fallback`."""
if isinstance(err, APIError):
raise HTTPException(status_code=err.status_code, detail=err.message) from err
raise HTTPException(status_code=500, detail=fallback) from err
def _user_payload(user: PublicUser) -> dict[str, Any]:
return {
"id": user.id,
"username": user.username,
"email": user.email,
"role": normalize_role(user.role),
"canManageUsers": can_manage_users(user.role),
"mfaEnabled": user.totp_enabled,
}
def _managed_user_payload(user: ManagedUser) -> dict[str, Any]:
return {
"id": user.id,
"username": user.username,
"email": user.email,
"role": normalize_role(user.role),
"createdAt": user.created_at,
}
def build_auth_router(
get_client: ClientGetter,
get_store: StoreGetter,
*,
legacy_cookie_name: str = "",
secure_cookie: bool = False,
cookie_name: str = DEFAULT_COOKIE_NAME,
2026-09-15 23:26:02 +02:00
configuration_error: str | None = None,
internal_secret: str | None = None,
local_profile_without_authguard: bool = False,
trusted_proxies: str | None = None,
) -> APIRouter:
"""Builds a ready-to-mount APIRouter implementing the full standardized
AuthGuard-proxy surface (no prefix baked in - mount it at "/api/auth",
matching every existing consumer). See the module docstring for the
`get_client`/`get_store` contract.
When `get_client` returns None (AUTHGUARD_URL unset) the guarded routes
refuse requests with a 500 unless `local_profile_without_authguard` is
True. Pass True only for a deployment that is meant to run without
AuthGuard; otherwise a missing environment variable would silently make
every guarded route run as the local superadmin.
Login and the TOTP routes refuse further attempts with 429: per account and per client
address for login (10 and 200 per 15 minutes), per user for TOTP verify and disable (5 per 15
minutes). The counters live in this process. The client address is the TCP peer;
`trusted_proxies` (default: the TRUSTED_PROXIES environment variable, a comma-separated list
of CIDR ranges or IP addresses, empty by default) names the reverse proxies whose
X-Forwarded-For is believed. An invalid list raises ValueError here, at startup. The address
is also sent to AuthGuard as X-Forwarded-For, which AuthGuard reads only from peers in its own
TRUSTED_PROXIES."""
router = APIRouter()
trusted_networks = (
trusted_proxies_from_env()
if trusted_proxies is None
else parse_trusted_proxies(trusted_proxies)
)
login_account_attempts = AttemptLimiter(ATTEMPT_WINDOW_SECONDS, LOGIN_ACCOUNT_LIMIT)
login_client_attempts = AttemptLimiter(ATTEMPT_WINDOW_SECONDS, LOGIN_CLIENT_LIMIT)
totp_attempts = AttemptLimiter(ATTEMPT_WINDOW_SECONDS, TOTP_ATTEMPT_LIMIT)
configured_internal_secret = (
os.environ.get("SECRET", "") if internal_secret is None else internal_secret
).strip()
2026-09-15 23:26:02 +02:00
def _ensure_configured() -> None:
if configuration_error:
raise HTTPException(status_code=500, detail=configuration_error)
def _enabled(client: Optional[AuthClient]) -> bool:
return client is not None
def _configured_client(
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
) -> Optional[AuthClient]:
"""Resolves the route's AuthClient. A missing client fails closed with a
500 unless running without AuthGuard was opted into."""
if client is None and not local_profile_without_authguard:
raise HTTPException(
status_code=500, detail=configuration_error or ERR_AUTHGUARD_NOT_CONFIGURED
)
return client
def _client_address(request: Request) -> str:
peer = request.client.host if request.client else ""
return client_address(peer, request.headers.getlist("x-forwarded-for"), trusted_networks)
def _session_token(request: Request) -> str:
return request.cookies.get(cookie_name, "") or ""
def _clear_session_cookies(response: Response) -> None:
names = [cookie_name]
if legacy_cookie_name and legacy_cookie_name != cookie_name:
names.append(legacy_cookie_name)
for name in names:
response.delete_cookie(
key=name, path="/", secure=secure_cookie, httponly=True, samesite="lax"
)
def _forward_cookies(response: Response, cookies: list[str]) -> None:
for cookie in cookies:
response.headers.append("set-cookie", cookie)
async def _current_profile(
request: Request, client: AuthClient
) -> tuple[Optional[PublicUser], str]:
token = _session_token(request)
if not token:
return None, ""
try:
user = await client.me(token)
except APIError as exc:
if exc.status_code == 401:
return None, ""
raise
return user, token
async def _current_profile_or_401(
request: Request, client: AuthClient
) -> tuple[PublicUser, str]:
try:
profile, token = await _current_profile(request, client)
except AuthClientError as exc:
raise HTTPException(status_code=500, detail=ERR_AUTHGUARD_UNAVAILABLE) from exc
if profile is None:
raise HTTPException(status_code=401, detail=ERR_AUTH_REQUIRED)
return profile, token
async def _login_required(store: ProxyStore) -> bool:
return await store.login_required()
async def require_session(
request: Request,
store: ProxyStore = Depends(get_store), # noqa: B008
client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
) -> PublicUser:
"""FastAPI dependency gating a route behind a valid session."""
if not _enabled(client) or not await _login_required(store):
return _LOCAL_PROFILE
assert client is not None
profile, _ = await _current_profile_or_401(request, client)
return profile
async def _require_user_manager(
request: Request,
store: ProxyStore = Depends(get_store), # noqa: B008
client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
) -> str:
"""Returns the caller's session token, or "" in auth-disabled mode
(each handler decides its own auth-disabled response). Authorization
(can_manage_users, "protect the superadmin") is enforced by
AuthGuard itself from the forwarded token."""
if not _enabled(client) or not await _login_required(store):
return ""
token = _session_token(request)
if not token:
raise HTTPException(status_code=401, detail=ERR_AUTH_REQUIRED)
return token
async def require_admin(
request: Request,
client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
) -> PublicUser:
"""FastAPI dependency gating a route behind an administrator session
(the Python counterpart of Go's RequireAdmin). Unlike require_session it
never falls back to _LOCAL_PROFILE, so a route that changes the
login-required flag cannot be called anonymously, even while login is
already disabled."""
if not _enabled(client):
raise HTTPException(status_code=401, detail=ERR_AUTH_REQUIRED)
assert client is not None
profile, _ = await _current_profile_or_401(request, client)
if not can_manage_users(profile.role):
raise HTTPException(status_code=403, detail=ERR_ADMIN_REQUIRED)
return profile
# --- status / me -------------------------------------------------------
@router.get("/me")
async def get_me(
request: Request,
store: ProxyStore = Depends(get_store), # noqa: B008
client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
) -> dict[str, Any]:
2026-09-15 23:26:02 +02:00
_ensure_configured()
login_required = await _login_required(store)
if not _enabled(client):
return {"user": _user_payload(_LOCAL_PROFILE), "authRequired": False}
if not login_required:
return {"user": _user_payload(_LOCAL_PROFILE), "authRequired": False}
assert client is not None
try:
profile, _ = await _current_profile(request, client)
except AuthClientError as exc:
raise HTTPException(status_code=500, detail=ERR_AUTHGUARD_UNAVAILABLE) from exc
return {
"user": _user_payload(profile) if profile else None,
"authRequired": login_required,
}
@router.get("/admin-needed")
async def get_admin_needed(
store: ProxyStore = Depends(get_store), # noqa: B008
client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
) -> dict[str, bool]:
if not _enabled(client):
return {"adminNeeded": False}
if not await _login_required(store):
return {"adminNeeded": False}
assert client is not None
if await store.is_setup_claimed():
return {"adminNeeded": False}
try:
setup_required = await client.setup_status()
except AuthClientError as exc:
raise HTTPException(status_code=500, detail=ERR_AUTHGUARD_UNAVAILABLE) from exc
return {"adminNeeded": setup_required}
@router.get("/status")
async def get_status(
request: Request,
store: ProxyStore = Depends(get_store), # noqa: B008
client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
) -> dict[str, Any]:
2026-09-15 23:26:02 +02:00
_ensure_configured()
if not _enabled(client):
return {
"setupRequired": False,
"authenticated": True,
"authRequired": False,
"user": _user_payload(_LOCAL_PROFILE),
}
assert client is not None
login_required = await _login_required(store)
if not login_required:
return {
"setupRequired": False,
"authenticated": True,
"authRequired": False,
"user": _user_payload(_LOCAL_PROFILE),
}
claimed = await store.is_setup_claimed()
setup_required = False
if not claimed:
try:
setup_required = await client.setup_status()
except AuthClientError as exc:
raise HTTPException(status_code=500, detail=ERR_AUTHGUARD_UNAVAILABLE) from exc
try:
profile, _ = await _current_profile(request, client)
except AuthClientError as exc:
raise HTTPException(status_code=500, detail=ERR_AUTHGUARD_UNAVAILABLE) from exc
return {
"setupRequired": setup_required,
"authenticated": profile is not None,
"authRequired": login_required,
"user": _user_payload(profile) if profile else None,
}
# --- setup / login / logout ---------------------------------------------
@router.post("/setup", status_code=201)
async def setup(
req: SetupRequest,
request: Request,
response: Response,
store: ProxyStore = Depends(get_store), # noqa: B008
client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
) -> dict[str, Any]:
if not _enabled(client):
return {"user": _user_payload(_LOCAL_PROFILE)}
assert client is not None
username = _normalize_username(req.username)
email = _normalize_email(req.email)
_validate_password(req.password)
if not await store.try_claim_setup():
raise HTTPException(status_code=409, detail=ERR_SETUP_COMPLETE)
try:
setup_required = await client.setup_status()
except AuthClientError as exc:
await store.unclaim_setup()
raise HTTPException(status_code=500, detail=ERR_AUTHGUARD_UNAVAILABLE) from exc
if not setup_required:
await store.unclaim_setup()
raise HTTPException(status_code=409, detail=ERR_SETUP_COMPLETE)
try:
with forwarded_client_ip(_client_address(request)):
result = await client.register(username, email, req.password)
except AuthClientError as exc:
await store.unclaim_setup()
_raise_authguard_error(exc, "Could not create account.")
raise # unreachable
_forward_cookies(response, result.cookies)
return {"user": _user_payload(result.user)}
@router.post("/login")
async def login(
req: LoginRequest,
request: Request,
response: Response,
client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
) -> dict[str, Any]:
if not _enabled(client):
return {"user": _user_payload(_LOCAL_PROFILE)}
assert client is not None
identifier = (req.identifier or req.username or req.email or "").strip()
if not identifier or len(identifier) > MAX_EMAIL_LEN:
raise HTTPException(status_code=401, detail=ERR_INVALID_CREDENTIALS)
address = _client_address(request)
account_ok = login_account_attempts.allow(identifier.lower())
if not (account_ok and login_client_attempts.allow(address)):
raise HTTPException(status_code=429, detail=ERR_TOO_MANY_ATTEMPTS)
try:
with forwarded_client_ip(address):
result = await client.login(identifier, req.password, req.totpToken)
except APIError as exc:
if exc.totp_required:
raise HTTPException(
status_code=401,
detail={
"error": "Two-factor authentication code required.",
"mfaRequired": True,
},
) from exc
if exc.status_code == 401:
raise HTTPException(status_code=401, detail=ERR_INVALID_CREDENTIALS) from exc
_raise_authguard_error(exc, "Could not authenticate.")
raise # unreachable
except AuthClientError as exc:
raise HTTPException(status_code=500, detail=ERR_AUTHGUARD_UNAVAILABLE) from exc
_forward_cookies(response, result.cookies)
return {"user": _user_payload(result.user)}
@router.post("/logout")
async def logout(
request: Request,
response: Response,
client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
) -> dict[str, bool]:
if _enabled(client):
assert client is not None
token = _session_token(request)
if token:
try:
cookies = await client.logout(token)
except APIError:
cookies = []
except AuthClientError as exc:
raise HTTPException(status_code=500, detail="Internal error.") from exc
else:
_forward_cookies(response, cookies)
_clear_session_cookies(response)
return {"ok": True}
# --- self-service profile editing ---------------------------------------
@router.put("/me")
@router.post("/me")
async def update_me(
req: UpdateMeRequest,
request: Request,
client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
) -> dict[str, Any]:
if not _enabled(client):
raise HTTPException(status_code=409, detail=ERR_FEATURE_REQUIRES_AUTHGUARD)
assert client is not None
current, token = await _current_profile_or_401(request, client)
if not can_manage_users(current.role):
raise HTTPException(status_code=403, detail=ERR_SELF_SERVICE_PROFILE)
email = _normalize_email(req.email)
username = _normalize_username(req.username)
password = None
if req.password:
_validate_password(req.password)
password = req.password
try:
await client.update_managed_user(
token, current.id, username=username, email=email, password=password
)
except AuthClientError as exc:
_raise_authguard_error(exc, "Profile could not be updated.")
raise # unreachable
try:
updated = await client.me(token)
except AuthClientError as exc:
raise HTTPException(status_code=500, detail="Profile could not be loaded.") from exc
return {"user": _user_payload(updated)}
# --- login-required toggle (only meaningful for a project that already
# has this concept locally; ProxyStore.login_required/set_login_required
# stub to (True, no-op) otherwise) --------------------------------------
@router.get("/access")
async def access_settings(store: ProxyStore = Depends(get_store)) -> dict[str, bool]: # noqa: B008
return {"loginRequired": await _login_required(store)}
@router.put("/access")
async def update_access_settings(
req: UpdateAccessRequest,
store: ProxyStore = Depends(get_store), # noqa: B008
_admin: PublicUser = Depends(require_admin), # noqa: B008
) -> dict[str, bool]:
await store.set_login_required(req.loginRequired)
return {"loginRequired": req.loginRequired}
@router.put("/access/internal")
async def update_access_settings_internal(
req: UpdateAccessRequest,
request: Request,
store: ProxyStore = Depends(get_store), # noqa: B008
) -> dict[str, bool]:
2026-09-18 13:11:49 +02:00
if (
not configured_internal_secret
or request.headers.get("X-Internal-Auth") != configured_internal_secret
):
raise HTTPException(status_code=401, detail="internal service authentication required")
await store.set_login_required(req.loginRequired)
return {"loginRequired": req.loginRequired}
# --- admin user management ----------------------------------------------
@router.get("/users")
async def list_users(
client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
token: str = Depends(_require_user_manager), # noqa: B008
) -> list[dict[str, Any]]:
if not _enabled(client):
return []
assert client is not None
try:
users = await client.list_managed_users(token)
except AuthClientError as exc:
_raise_authguard_error(exc, "Users unavailable.")
raise # unreachable
return [_managed_user_payload(u) for u in users]
@router.post("/users", status_code=201)
async def create_managed_user(
req: ManagedUserRequest,
client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
token: str = Depends(_require_user_manager), # noqa: B008
) -> dict[str, Any]:
if not _enabled(client):
raise HTTPException(status_code=409, detail=ERR_FEATURE_REQUIRES_AUTHGUARD)
assert client is not None
try:
created = await client.create_managed_user(
token, username=req.username, email=req.email, password=req.password, role=req.role
)
except AuthClientError as exc:
_raise_authguard_error(exc, "User could not be created.")
raise # unreachable
return _managed_user_payload(created)
@router.put("/users/{user_id}")
@router.patch("/users/{user_id}")
async def update_managed_user(
user_id: int,
req: ManagedUserRequest,
client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
token: str = Depends(_require_user_manager), # noqa: B008
) -> dict[str, Any]:
if not _enabled(client):
raise HTTPException(status_code=409, detail=ERR_FEATURE_REQUIRES_AUTHGUARD)
assert client is not None
try:
await client.update_managed_user(
token,
user_id,
username=req.username or None,
email=req.email or None,
password=req.password or None,
role=req.role,
)
except AuthClientError as exc:
_raise_authguard_error(exc, "User could not be updated.")
raise # unreachable
try:
users = await client.list_managed_users(token)
except AuthClientError as exc:
_raise_authguard_error(exc, "User could not be loaded.")
raise # unreachable
updated = next((u for u in users if u.id == user_id), None)
if updated is None:
raise HTTPException(status_code=404, detail="User not found.")
return _managed_user_payload(updated)
@router.delete("/users/{user_id}")
async def delete_managed_user(
user_id: int,
client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
token: str = Depends(_require_user_manager), # noqa: B008
) -> dict[str, bool]:
if not _enabled(client):
raise HTTPException(status_code=409, detail=ERR_FEATURE_REQUIRES_AUTHGUARD)
assert client is not None
try:
await client.delete_managed_user(token, user_id)
except AuthClientError as exc:
_raise_authguard_error(exc, "User could not be deleted.")
raise # unreachable
return {"ok": True}
# --- TOTP ----------------------------------------------------------------
@router.get("/totp/status")
async def get_totp_status(
request: Request,
client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
) -> dict[str, bool]:
if not _enabled(client):
return {"enabled": False, "mfaEnabled": False}
assert client is not None
profile, _ = await _current_profile_or_401(request, client)
return {"enabled": bool(profile.totp_enabled), "mfaEnabled": bool(profile.totp_enabled)}
@router.post("/totp/initiate")
async def initiate_totp(
request: Request,
client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
) -> dict[str, Any]:
if not _enabled(client):
raise HTTPException(status_code=409, detail=ERR_FEATURE_REQUIRES_AUTHGUARD)
assert client is not None
profile, token = await _current_profile_or_401(request, client)
if profile.totp_enabled:
raise HTTPException(
status_code=409, detail="Two-factor authentication is already enabled."
)
try:
result = await client.totp_enable(token)
except AuthClientError as exc:
_raise_authguard_error(exc, "Could not create authenticator secret.")
raise # unreachable
return {
"data": {
"secret": result.secret,
"otpauth": result.otpauth_url,
"otpauthUrl": result.otpauth_url,
"enabled": result.enabled,
}
}
@router.post("/totp/verify")
async def verify_totp(
req: TotpTokenRequest,
request: Request,
client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
) -> dict[str, Any]:
if not _enabled(client):
raise HTTPException(status_code=409, detail=ERR_FEATURE_REQUIRES_AUTHGUARD)
assert client is not None
profile, token = await _current_profile_or_401(request, client)
if not totp_attempts.allow(str(profile.id)):
raise HTTPException(status_code=429, detail=ERR_TOO_MANY_ATTEMPTS)
code = req.totpToken or req.token
try:
with forwarded_client_ip(_client_address(request)):
await client.totp_verify(token, code)
except Exception as exc:
raise HTTPException(status_code=401, detail="Invalid authenticator code.") from exc
return {"data": {"mfaEnabled": True, "enabled": True, "backupCodes": []}}
@router.post("/totp/disable")
async def disable_totp(
req: TotpTokenRequest,
request: Request,
client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
) -> dict[str, Any]:
if not _enabled(client):
raise HTTPException(status_code=409, detail=ERR_FEATURE_REQUIRES_AUTHGUARD)
assert client is not None
profile, token = await _current_profile_or_401(request, client)
if not totp_attempts.allow(str(profile.id)):
raise HTTPException(status_code=429, detail=ERR_TOO_MANY_ATTEMPTS)
code = req.totpToken or req.token
try:
with forwarded_client_ip(_client_address(request)):
await client.totp_disable(token, code)
except Exception as exc:
raise HTTPException(status_code=401, detail="Invalid authenticator code.") from exc
return {"data": {"mfaEnabled": False, "enabled": False}}
# Expose the session dependency for the project's own non-auth routes to
# reuse (mirrors Go's Service.Require/RequireAdmin being usable as
# middleware on any route, not just this router's own).
2026-09-28 22:28:53 +02:00
router.require_session = require_session # ty: ignore[unresolved-attribute]
return router