136 lines
4.4 KiB
Python
136 lines
4.4 KiB
Python
"""
|
|
FastAPI Security & Authentication Dependencies
|
|
Handles JWT extraction from HttpOnly cookies and Bearer headers,
|
|
and implements declarative RBAC validation with app context.
|
|
"""
|
|
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
|
|
from database import get_flask_app
|
|
|
|
flask_app = get_flask_app()
|
|
|
|
|
|
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."
|
|
)
|
|
|
|
with flask_app.app_context():
|
|
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."
|
|
)
|
|
|
|
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:
|
|
with flask_app.app_context():
|
|
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).
|
|
Normaliza comparaciones en minúsculas y reconoce equivalencias (ADMIN, Bedelia, etc.).
|
|
"""
|
|
normalized_allowed = [r.lower() for r in allowed_roles]
|
|
|
|
def role_dependency(user: User = Depends(get_current_user)) -> User:
|
|
user_role = (user.role or '').lower()
|
|
is_admin = getattr(user, 'is_admin', lambda: False)() or user_role in ['admin', 'administrador']
|
|
|
|
if is_admin and ('admin' in normalized_allowed or 'administrador' in normalized_allowed):
|
|
return user
|
|
|
|
if user_role in normalized_allowed:
|
|
return user
|
|
|
|
raise HTTPException(
|
|
status_code=status.HTTP_403_FORBIDDEN,
|
|
detail=f"Acceso denegado. Se requiere uno de los siguientes roles: {', '.join(allowed_roles)}."
|
|
)
|
|
|
|
return role_dependency
|
|
|
|
|
|
async def get_request_payload(request: Request) -> dict[str, Any]:
|
|
"""Extrae el cuerpo JSON o formulario multiparte sanitizado como diccionario de Python."""
|
|
try:
|
|
body = await request.json()
|
|
if isinstance(body, dict):
|
|
return body
|
|
except Exception:
|
|
pass
|
|
try:
|
|
form = await request.form()
|
|
return {k: str(v) for k, v in form.items()}
|
|
except Exception:
|
|
return {}
|