api / app /dependencies.py
Mate11
Agregar logging detallado en auth, servicios y routers
58e4c2a
Raw History Blame Contribute Delete
3.93 kB
"""
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:
"""
Valida la sesión de M6: siempre un JWT HS256 propio (`jwt_secret`),
emitido al hacer login o al canjear un ticket SSO del Core
(`app/routers/auth.py`). El rol ya viaja en el token — no hay
verificación contra el Core ni lookup de roles en cada request.
"""
if credentials is None:
logger.warning("Intento de acceso sin token de autenticación")
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:
logger.warning("Token válido pero sin campos requeridos (sub/rol) — payload keys: %s", list(payload.keys()))
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:
user_rol = user.get("rol")
if user_rol not in roles:
logger.warning(
"Acceso denegado (403) — user_id=%s rol=%s requiere uno de %s",
user.get("sub"), user_rol, roles,
)
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=_ERROR_403)
return user
return checker