feat(migration): v3.8.0 - erradicacion total de flask, persistencia nativa sqlalchemy 2.0 y compatibilidad pura fastapi
This commit is contained in:
+62
-48
@@ -1,7 +1,8 @@
|
||||
"""
|
||||
FastAPI Security & Authentication Dependencies
|
||||
Handles JWT extraction from HttpOnly cookies and Bearer headers,
|
||||
and implements declarative RBAC validation with app context.
|
||||
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
|
||||
@@ -9,9 +10,6 @@ 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]:
|
||||
@@ -59,24 +57,33 @@ def get_current_user(request: Request) -> User:
|
||||
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."
|
||||
)
|
||||
|
||||
# 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:
|
||||
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)}"
|
||||
)
|
||||
target_user = User.query.get(int(impersonate_header))
|
||||
if target_user and target_user.is_active:
|
||||
return target_user
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if not user or not user.is_active:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Usuario inactivo o no encontrado."
|
||||
)
|
||||
|
||||
return user
|
||||
return user
|
||||
|
||||
|
||||
def get_optional_current_user(request: Request) -> Optional[User]:
|
||||
@@ -88,8 +95,7 @@ def get_optional_current_user(request: Request) -> Optional[User]:
|
||||
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))
|
||||
return User.query.get(int(user_id))
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
@@ -98,38 +104,46 @@ def get_optional_current_user(request: Request) -> Optional[User]:
|
||||
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.).
|
||||
Permite acceso si el rol del usuario (normalizado en mayúsculas) coincide
|
||||
con alguno de los roles permitidos.
|
||||
"""
|
||||
normalized_allowed = [r.lower() for r in allowed_roles]
|
||||
normalized_allowed = [r.upper() 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']
|
||||
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
|
||||
|
||||
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
|
||||
return role_checker
|
||||
|
||||
|
||||
async def get_request_payload(request: Request) -> dict[str, Any]:
|
||||
"""Extrae el cuerpo JSON o formulario multiparte sanitizado como diccionario de Python."""
|
||||
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 dict(form)
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
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()}
|
||||
return body if isinstance(body, dict) else {}
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
Reference in New Issue
Block a user