|
| 1 | +"""Auth dependencies: resolve the crudauth ``Principal`` and the dict-compat user. |
| 2 | +
|
| 3 | +Routes depend on these; they wrap the crudauth ``auth`` singleton so the session |
| 4 | +engine (validation, CSRF, lockout) lives in crudauth while handlers keep their |
| 5 | +existing dict/Principal contracts. ``get_current_user`` returns the same user |
| 6 | +dict the rest of the app (and the API-key module) already consumes, so the public |
| 7 | +contract is unchanged. |
| 8 | +""" |
| 9 | + |
| 10 | +from typing import Annotated, Any |
| 11 | + |
| 12 | +from crudauth import Principal |
| 13 | +from crudauth.exceptions import ForbiddenException, UnauthorizedException |
| 14 | +from fastapi import Depends |
| 15 | +from sqlalchemy.ext.asyncio import AsyncSession |
| 16 | + |
| 17 | +from ...modules.user.crud import crud_users |
| 18 | +from ..database.session import async_session |
| 19 | +from .setup import auth |
| 20 | + |
| 21 | + |
| 22 | +async def get_current_principal( |
| 23 | + principal: Annotated[Principal, Depends(auth.current_user())], |
| 24 | +) -> Principal: |
| 25 | + """The authenticated crudauth ``Principal`` (session-validated, CSRF-enforced). |
| 26 | +
|
| 27 | + A single named dependency so routes that need the session id |
| 28 | + (``principal.metadata["session_id"]``) or the transport can depend on it and |
| 29 | + tests can override it. Raises 401 when there is no valid session. |
| 30 | + """ |
| 31 | + return principal |
| 32 | + |
| 33 | + |
| 34 | +async def get_optional_principal( |
| 35 | + principal: Annotated[Principal | None, Depends(auth.current_user(optional=True))], |
| 36 | +) -> Principal | None: |
| 37 | + """The crudauth ``Principal`` if authenticated, else ``None`` (never raises on absence). |
| 38 | +
|
| 39 | + Still enforces CSRF on unsafe methods when a session is present. |
| 40 | + """ |
| 41 | + return principal |
| 42 | + |
| 43 | + |
| 44 | +async def get_current_user( |
| 45 | + principal: Annotated[Principal | None, Depends(get_optional_principal)], |
| 46 | + db: Annotated[AsyncSession, Depends(async_session)], |
| 47 | +) -> dict[str, Any]: |
| 48 | + """Get the current authenticated user as a dict (resolved by crudauth). |
| 49 | +
|
| 50 | + crudauth validates the cookie and enforces CSRF on unsafe methods; we re-load |
| 51 | + the full row (filtering soft-deleted users) so the return value stays the dict |
| 52 | + the handlers expect. |
| 53 | +
|
| 54 | + Raises: |
| 55 | + UnauthorizedException: If not authenticated or the user doesn't exist. |
| 56 | + """ |
| 57 | + credentials_exception = UnauthorizedException("Not authenticated") |
| 58 | + |
| 59 | + if principal is None: |
| 60 | + raise credentials_exception |
| 61 | + |
| 62 | + user = await crud_users.get(db=db, id=principal.user_id, is_deleted=False) |
| 63 | + |
| 64 | + if user is None: |
| 65 | + raise credentials_exception |
| 66 | + |
| 67 | + return user |
| 68 | + |
| 69 | + |
| 70 | +async def get_optional_user( |
| 71 | + principal: Annotated[Principal | None, Depends(get_optional_principal)], |
| 72 | + db: Annotated[AsyncSession, Depends(async_session)], |
| 73 | +) -> dict[str, Any] | None: |
| 74 | + """Get the current user as a dict if authenticated, None otherwise.""" |
| 75 | + if principal is None: |
| 76 | + return None |
| 77 | + |
| 78 | + return await crud_users.get(db=db, id=principal.user_id, is_deleted=False) |
| 79 | + |
| 80 | + |
| 81 | +async def get_current_superuser( |
| 82 | + current_user: Annotated[dict[str, Any], Depends(get_current_user)], |
| 83 | +) -> dict[str, Any]: |
| 84 | + """Get the current user as a dict, requiring superuser privileges (403 otherwise).""" |
| 85 | + if not current_user.get("is_superuser", False): |
| 86 | + raise ForbiddenException("Insufficient privileges") |
| 87 | + |
| 88 | + return current_user |
0 commit comments