File size: 3,926 Bytes
5f12c93
2ad902b
5f12c93
 
 
 
 
 
 
2ad902b
5f12c93
 
 
 
 
 
 
2ad902b
 
5f12c93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c5d6e7
 
 
 
5f12c93
 
 
 
 
 
2c5d6e7
5f12c93
624c7c9
 
 
 
 
 
2c5d6e7
58e4c2a
2c5d6e7
e6a43c8
5f12c93
 
 
 
 
 
58e4c2a
5f12c93
 
 
 
 
 
 
 
 
 
58e4c2a
 
 
 
 
 
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
"""
Dependencias compartidas de FastAPI: BD (Supabase), JWT y autenticación.
"""
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 supabase import create_client, Client

from app.config import settings

logger = logging.getLogger(__name__)

# ─── Base de datos ─────────────────────────────────────────────────────────

def get_db() -> Client:
    return create_client(settings.supabase_url, settings.supabase_key)


# ─── 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 ───────────────────────────────────────────────────────────

# auto_error=False: sin esto, HTTPBearer responde 403 ante un token ausente.
# El contrato (§12) exige 401 para "sin token / token inválido", así que
# manejamos el caso None nosotros y devolvemos 401 de forma consistente.
_security = HTTPBearer(auto_error=False)

_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 | None = Depends(_security),
) -> dict:
    """
    Valida la sesión de M6: siempre un JWT HS256 propio (`jwt_secret`),
    emitido al hacer login o al canjear un ticket SSO del Core
    (`app/routers/auth.py`). El rol ya viaja en el token — no hay
    verificación contra el Core ni lookup de roles en cada request.
    """
    if credentials is None:
        logger.warning("Intento de acceso sin token de autenticación")
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=_ERROR_401)

    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:
        logger.warning("Token válido pero sin campos requeridos (sub/rol) — payload keys: %s", list(payload.keys()))
        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:
        user_rol = user.get("rol")
        if user_rol not in roles:
            logger.warning(
                "Acceso denegado (403) — user_id=%s rol=%s requiere uno de %s",
                user.get("sub"), user_rol, roles,
            )
            raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=_ERROR_403)
        return user
    return checker