""" Dependencias compartidas de FastAPI: BD (Supabase), JWT y autenticación. """ import logging from datetime import datetime, timedelta, timezone from fastapi import Depends, HTTPException, status from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials from jose import JWTError, jwt from supabase import create_client, Client from app.config import settings logger = logging.getLogger(__name__) # ─── Base de datos ───────────────────────────────────────────────────────── def get_db() -> Client: return create_client(settings.supabase_url, settings.supabase_key) # ─── JWT ─────────────────────────────────────────────────────────────────── def create_access_token(sub: str, rol: str, extra: dict | None = None) -> str: now = datetime.now(timezone.utc) payload = { "sub": str(sub), "rol": rol, "iat": now, "exp": now + timedelta(minutes=settings.jwt_expire_minutes), } if extra: payload.update(extra) return jwt.encode(payload, settings.jwt_secret, algorithm=settings.jwt_algorithm) def decode_token(token: str) -> dict: try: return jwt.decode( token, settings.jwt_secret, algorithms=[settings.jwt_algorithm], ) except JWTError as e: logger.warning("Intento de autenticación con token inválido: %s", e) raise ValueError("Token inválido") # ─── Auth FastAPI ─────────────────────────────────────────────────────────── # auto_error=False: sin esto, HTTPBearer responde 403 ante un token ausente. # El contrato (§12) exige 401 para "sin token / token inválido", así que # manejamos el caso None nosotros y devolvemos 401 de forma consistente. _security = HTTPBearer(auto_error=False) _ERROR_401 = {"codigo": "NO_AUTENTICADO", "mensaje": "Token ausente, expirado o malformado"} _ERROR_403 = {"codigo": "NO_AUTORIZADO", "mensaje": "No tiene permisos para esta operación"} def get_current_user( credentials: HTTPAuthorizationCredentials | None = Depends(_security), ) -> dict: if credentials is None: raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=_ERROR_401) try: payload = decode_token(credentials.credentials) except ValueError: raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=_ERROR_401) if "sub" not in payload or "rol" not in payload: raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=_ERROR_401) return payload def require_roles(*roles: str): """ Uso: Depends(require_roles("ADMINISTRATIVO", "MEDICO")) """ def checker(user: dict = Depends(get_current_user)) -> dict: if user.get("rol") not in roles: raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=_ERROR_403) return user return checker