150 lines
5.0 KiB
Python
150 lines
5.0 KiB
Python
"""
|
|
FastAPI Security & Authentication Dependencies
|
|
Handles JWT extraction from HttpOnly cookies and Bearer headers,
|
|
and implements declarative RBAC validation with native SQLAlchemy.
|
|
100% Native FastAPI - Zero Flask dependencies.
|
|
"""
|
|
from typing import Optional, List, Callable, Any, Dict
|
|
from fastapi import Request, HTTPException, Depends, status
|
|
import jwt
|
|
|
|
from app.models.user import User
|
|
from app.services.jwt_service import JWTService
|
|
|
|
|
|
def get_token_from_request(request: Request) -> Optional[str]:
|
|
"""Extrae el token JWT desde cookies HttpOnly o cabecera Authorization Bearer."""
|
|
token = request.cookies.get('access_token')
|
|
if token:
|
|
return token
|
|
|
|
auth_header = request.headers.get('Authorization')
|
|
if auth_header and auth_header.startswith('Bearer '):
|
|
return auth_header.split(' ', 1)[1].strip()
|
|
|
|
return None
|
|
|
|
|
|
def get_current_user(request: Request) -> User:
|
|
"""
|
|
Dependencia FastAPI que resuelve y autentica al usuario actual.
|
|
Lanza HTTP 401 si no hay token, si es inválido o si el usuario no existe.
|
|
"""
|
|
token = get_token_from_request(request)
|
|
if not token:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="No se proporcionó token de autenticación."
|
|
)
|
|
|
|
try:
|
|
payload = JWTService.decode_token(token, expected_type='access')
|
|
except jwt.ExpiredSignatureError:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="El token de acceso ha expirado."
|
|
)
|
|
except jwt.PyJWTError as e:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail=f"Token inválido: {str(e)}"
|
|
)
|
|
|
|
user_id = payload.get('sub')
|
|
if not user_id:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Token no contiene identificador de usuario válido."
|
|
)
|
|
|
|
try:
|
|
user = User.query.get(int(user_id))
|
|
if user:
|
|
_ = getattr(user, 'role_obj', None)
|
|
except Exception as e:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
detail=f"Error consultando usuario: {str(e)}"
|
|
)
|
|
|
|
if not user or not user.is_active:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Usuario inactivo o no encontrado."
|
|
)
|
|
|
|
# Soporte para auditoría/impersonación mediante cabecera X-Impersonate-User
|
|
impersonate_header = request.headers.get('X-Impersonate-User')
|
|
if impersonate_header and (user.role or '').upper() == 'ADMIN':
|
|
try:
|
|
target_user = User.query.get(int(impersonate_header))
|
|
if target_user and target_user.is_active:
|
|
return target_user
|
|
except Exception:
|
|
pass
|
|
|
|
return user
|
|
|
|
|
|
def get_optional_current_user(request: Request) -> Optional[User]:
|
|
"""Dependencia opcional: retorna el usuario autenticado o None si es anónimo."""
|
|
token = get_token_from_request(request)
|
|
if not token:
|
|
return None
|
|
try:
|
|
payload = JWTService.decode_token(token, expected_type='access')
|
|
user_id = payload.get('sub')
|
|
if user_id:
|
|
return User.query.get(int(user_id))
|
|
except Exception:
|
|
pass
|
|
return None
|
|
|
|
|
|
def require_roles(allowed_roles: List[str]) -> Callable:
|
|
"""
|
|
Factory de dependencias para control de acceso basado en roles (RBAC).
|
|
Permite acceso si el rol del usuario (normalizado en mayúsculas) coincide
|
|
con alguno de los roles permitidos.
|
|
"""
|
|
normalized_allowed = [r.upper() for r in allowed_roles]
|
|
|
|
def role_checker(current_user: User = Depends(get_current_user)) -> User:
|
|
user_role = (current_user.role or '').upper()
|
|
if user_role not in normalized_allowed:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_403_FORBIDDEN,
|
|
detail=f"Acceso denegado. Se requiere uno de los roles: {', '.join(allowed_roles)}."
|
|
)
|
|
return current_user
|
|
|
|
return role_checker
|
|
|
|
|
|
async def get_request_payload(request: Request) -> Dict[str, Any]:
|
|
"""
|
|
Función de utilidad desacoplada para extraer el payload de la petición HTTP,
|
|
admitiendo indistintamente cuerpos con JSON (application/json) o formularios codificados
|
|
en application/x-www-form-urlencoded y multipart/form-data.
|
|
"""
|
|
content_type = request.headers.get("content-type", "").lower()
|
|
if "application/json" in content_type:
|
|
try:
|
|
body = await request.json()
|
|
return body if isinstance(body, dict) else {}
|
|
except Exception:
|
|
return {}
|
|
|
|
if "application/x-www-form-urlencoded" in content_type or "multipart/form-data" in content_type:
|
|
try:
|
|
form = await request.form()
|
|
return {k: str(v) for k, v in form.items()}
|
|
except Exception:
|
|
return {}
|
|
|
|
try:
|
|
body = await request.json()
|
|
return body if isinstance(body, dict) else {}
|
|
except Exception:
|
|
return {}
|