Spaces:
Sleeping
Sleeping
Download src/auth.py from puzan789/mcq: direct link, hf CLI and curl.
- Browser
- Download file 3.81 kB
-
https://huggingface.co/spaces/puzan789/mcq/resolve/main/src/auth.py
- Command line
-
hf download hf://spaces/puzan789/mcq/src/auth.py
-
curl -L -o auth.py https://huggingface.co/spaces/puzan789/mcq/resolve/main/src/auth.py
3.81 kB
| """ | |
| Shared-secret auth for the whole backend. | |
| Only the Next.js server ever calls this service: its client is `server-only`, | |
| so the key lives in the site's server environment and never reaches a browser. | |
| That makes a static bearer token the right shape here , per-user authorization | |
| already happened in the site's proxy, against Supabase, before the request was | |
| made. | |
| """ | |
| import hmac | |
| from starlette.datastructures import Headers | |
| from src.config import settings | |
| _BEARER = "bearer " | |
| def presented_key(headers: Headers) -> str | None: | |
| """The key from `Authorization: Bearer <key>`, or the `X-API-Key` fallback.""" | |
| authorization = headers.get("authorization", "") | |
| if authorization.lower().startswith(_BEARER): | |
| return authorization[len(_BEARER) :].strip() or None | |
| return headers.get("x-api-key") or None | |
| def key_matches(candidate: str | None) -> bool: | |
| """Constant-time compare, so a wrong key cannot be found a byte at a time.""" | |
| if not settings.api_key or not candidate: | |
| return False | |
| return hmac.compare_digest(candidate, settings.api_key) | |
| # ---------------------------------------------------------------- user JWT --- | |
| # The service key above proves the caller is the site. This proves *which | |
| # person* the site is acting for, so the mutating endpoints do not simply take | |
| # the proxy's word that someone was an admin. | |
| import jwt | |
| from fastapi import HTTPException, Request | |
| from jwt import PyJWKClient | |
| from loguru import logger | |
| _ASYMMETRIC = ("ES256", "RS256") | |
| _jwks_client: PyJWKClient | None = None | |
| def _jwks() -> PyJWKClient: | |
| """Cached JWKS client. Fetches once, then verifies offline until keys rotate.""" | |
| global _jwks_client | |
| if _jwks_client is None: | |
| if not settings.supabase_url: | |
| raise HTTPException(status_code=503, detail="SUPABASE_URL is not configured.") | |
| url = settings.supabase_url.rstrip("/") + "/auth/v1/.well-known/jwks.json" | |
| _jwks_client = PyJWKClient(url, cache_keys=True) | |
| return _jwks_client | |
| def verify_user_token(token: str) -> dict: | |
| """Decode and verify a Supabase access token. Raises 401 on anything wrong.""" | |
| issuer = (settings.supabase_url or "").rstrip("/") + "/auth/v1" | |
| common = { | |
| "audience": "authenticated", | |
| "issuer": issuer, | |
| "leeway": settings.jwt_leeway_seconds, | |
| "options": {"require": ["exp", "sub"]}, | |
| } | |
| try: | |
| if settings.jwt_secret: | |
| # Legacy projects: symmetric, shared secret. | |
| return jwt.decode(token, settings.jwt_secret, algorithms=["HS256"], **common) | |
| key = _jwks().get_signing_key_from_jwt(token).key | |
| return jwt.decode(token, key, algorithms=list(_ASYMMETRIC), **common) | |
| except HTTPException: | |
| raise | |
| except jwt.ExpiredSignatureError: | |
| raise HTTPException(status_code=401, detail="Session expired. Sign in again.") | |
| except Exception as error: | |
| logger.warning("Rejected a user token: {}", error) | |
| raise HTTPException(status_code=401, detail="Invalid session token.") | |
| async def require_admin(request: Request) -> dict: | |
| """ | |
| FastAPI dependency for the endpoints that read or change the corpus. | |
| The token travels in its own header: Authorization already carries the | |
| service key, and conflating the two would make one able to stand in for the | |
| other. | |
| """ | |
| token = request.headers.get("x-user-token") | |
| if not token: | |
| raise HTTPException(status_code=401, detail="Admin sign-in required.") | |
| claims = verify_user_token(token) | |
| # app_metadata is service-role writable only; user_metadata is not, and must | |
| # never decide this. | |
| if (claims.get("app_metadata") or {}).get("role") != "admin": | |
| raise HTTPException(status_code=403, detail="Admin access required.") | |
| return claims | |