feat(api): migracion completa de Flask API a FastAPI ASGI con arquitectura en 4 capas v3.6.0
This commit is contained in:
@@ -0,0 +1,119 @@
|
||||
"""
|
||||
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
|
||||
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():
|
||||
from sqlalchemy.orm import joinedload
|
||||
try:
|
||||
user = User.query.options(joinedload(User.role_obj)).get(int(user_id))
|
||||
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
|
||||
Reference in New Issue
Block a user