File size: 3,306 Bytes
5f12c93 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 | """
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
|