""" Dependencias compartidas de FastAPI: BD, JWT y autenticación. Unifica database.py + auth/jwt_handler.py + auth/dependencies.py del proyecto original. """ 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 sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker, Session, DeclarativeBase from app.config import settings logger = logging.getLogger(__name__) # ─── Base de datos ───────────────────────────────────────────────────────── engine = create_engine( settings.database_url, pool_pre_ping=True, pool_size=5, max_overflow=10, ) SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) class Base(DeclarativeBase): pass def get_db(): db = SessionLocal() try: yield db except Exception: db.rollback() raise finally: db.close() # ─── 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 ─────────────────────────────────────────────────────────── _security = HTTPBearer() _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 = Depends(_security), ) -> dict: 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