Spaces:
Running
Running
Download core/auth/deps.py from Aynkhn/WorkPilot-AI: direct link, hf CLI and curl.
- Browser
- Download file 2.01 kB
-
https://huggingface.co/spaces/Aynkhn/WorkPilot-AI/resolve/main/core/auth/deps.py
- Command line
-
hf download hf://spaces/Aynkhn/WorkPilot-AI/core/auth/deps.py
-
curl -L -o deps.py https://huggingface.co/spaces/Aynkhn/WorkPilot-AI/resolve/main/core/auth/deps.py
2.01 kB
| """FastAPI dependencies: current principal and role checks.""" | |
| from __future__ import annotations | |
| import uuid | |
| from collections.abc import Awaitable, Callable | |
| from dataclasses import dataclass | |
| from fastapi import Depends, Header, HTTPException, Request, status | |
| from core.auth.jwt import TokenError, decode_token | |
| from core.db.session import Database | |
| from core.tenancy.models import ROLE_RANK, Role | |
| from core.tenancy.service import role_in | |
| class Principal: | |
| user_id: uuid.UUID | |
| tenant_id: uuid.UUID | |
| role: Role | |
| def actor(self) -> str: | |
| return f"user:{self.user_id}" | |
| def get_db(request: Request) -> Database: | |
| db: Database = request.app.state.db | |
| return db | |
| async def current_principal( | |
| authorization: str = Header(default=""), | |
| db: Database = Depends(get_db), | |
| ) -> Principal: | |
| scheme, _, token = authorization.partition(" ") | |
| if scheme.lower() != "bearer" or not token: | |
| raise HTTPException(status.HTTP_401_UNAUTHORIZED, "missing bearer token") | |
| try: | |
| payload = decode_token(token, "access") | |
| except TokenError as exc: | |
| raise HTTPException(status.HTTP_401_UNAUTHORIZED, "invalid token") from exc | |
| if not payload.get("tid"): | |
| raise HTTPException(status.HTTP_401_UNAUTHORIZED, "token has no tenant") | |
| user_id, tenant_id = uuid.UUID(payload["sub"]), uuid.UUID(payload["tid"]) | |
| role = await role_in(db, user_id, tenant_id) | |
| if role is None: | |
| raise HTTPException(status.HTTP_403_FORBIDDEN, "not a member of this tenant") | |
| return Principal(user_id=user_id, tenant_id=tenant_id, role=role) | |
| def require_role(minimum: Role) -> Callable[..., Awaitable[Principal]]: | |
| async def _dep(p: Principal = Depends(current_principal)) -> Principal: | |
| if ROLE_RANK[p.role] < ROLE_RANK[minimum]: | |
| raise HTTPException(status.HTTP_403_FORBIDDEN, f"requires role {minimum.value}") | |
| return p | |
| return _dep | |