Download app/integrations/core_auth.py from Modulo-6/api: direct link, hf CLI and curl.
- Browser
- Download file 5.83 kB
-
https://huggingface.co/spaces/Modulo-6/api/resolve/abb37522de5ae43d93dfdca315ce81b830ce312c/app/integrations/core_auth.py
- Command line
-
hf download hf://spaces/Modulo-6/api@abb37522de5ae43d93dfdca315ce81b830ce312c/app/integrations/core_auth.py
-
curl -L -o core_auth.py https://huggingface.co/spaces/Modulo-6/api/resolve/abb37522de5ae43d93dfdca315ce81b830ce312c/app/integrations/core_auth.py
5.83 kB
| """ | |
| M10 Core — integración de autenticación real: canje de ticket SSO y cuenta | |
| de servicio de M6. | |
| La sesión de M6 es siempre un JWT HS256 propio (`app/dependencies.py`, | |
| `create_access_token`/`decode_token`). El Core se toca en dos puntos nada | |
| más: (a) el canje del ticket SSO (`exchange_sso_ticket`, una vez por login), | |
| y (b) la cuenta de servicio para las llamadas salientes de M6 a M1/M2/M7. | |
| No hay verificación de JWT del Core por-request ni lookup de roles — el rol | |
| se resuelve una sola vez, en el canje, a partir de `user.roles[]` (ver | |
| `app/routers/auth.py`). | |
| """ | |
| import logging | |
| import time | |
| import httpx | |
| from jose import JWTError, jwt | |
| from app.config import settings | |
| logger = logging.getLogger(__name__) | |
| # ─── Canje de ticket SSO ──────────────────────────────────────────────────── | |
| class SSOTicketInvalid(Exception): | |
| """Ticket ausente/inválido/ya usado/expirado (el Core respondió 400/401).""" | |
| class SSOExchangeError(Exception): | |
| """Fallo al comunicarse con el Core (red, timeout, 5xx, etc.).""" | |
| def exchange_sso_ticket(ticket: str) -> dict: | |
| """ | |
| Canjea un ticket SSO de un solo uso contra el Core por `{user, token}` | |
| (`POST /auth/sso-exchange`, `models.AuthResponse`). `user.roles[]` trae | |
| el/los rol(es) del usuario en el Core — de ahí sale la autorización de | |
| M6, sin necesidad de un lookup aparte. | |
| """ | |
| url = f"{settings.m10_core_url}/auth/sso-exchange" | |
| try: | |
| r = httpx.post(url, json={"ticket": ticket}, timeout=settings.http_timeout_seconds) | |
| except httpx.HTTPError as e: | |
| raise SSOExchangeError("No se pudo contactar al Core para el canje SSO") from e | |
| if r.status_code == 401: | |
| raise SSOTicketInvalid("Ticket inválido, ya usado o expirado") | |
| if r.status_code == 400: | |
| raise SSOTicketInvalid("Falta el ticket en el request") | |
| if r.status_code >= 400: | |
| raise SSOExchangeError(f"El Core respondió {r.status_code} al canjear el ticket SSO") | |
| return r.json() | |
| # ─── Cuenta de servicio de M6 ─────────────────────────────────────────────── | |
| # Token de la cuenta de servicio de M6 en el Core. Se usa para firmar las | |
| # llamadas salientes a M1/M2/M7/M10 (adjuntado automáticamente por | |
| # `app/integrations/_base.py`), incluidas las disparadas por webhooks | |
| # entrantes donde no hay un usuario humano autenticado. | |
| _service_token_cache: dict = {"token": None, "expires_at": 0.0} | |
| # Margen de expiración: se renueva el token antes de que venza de verdad, | |
| # para no arriesgar un 401 a mitad de una llamada saliente. | |
| _SERVICE_TOKEN_EXPIRY_MARGIN_SECONDS = 30 | |
| def get_service_token() -> str | None: | |
| """ | |
| Devuelve un token válido de la cuenta de servicio de M6, refrescándolo si | |
| expiró o no se pidió todavía. `None` si faltan las credenciales de | |
| servicio (`CORE_SERVICE_EMAIL`/`_PASSWORD`) — el llamador debe seguir sin | |
| el header `Authorization` en ese caso. | |
| """ | |
| if not settings.core_service_email or not settings.core_service_password: | |
| logger.warning( | |
| "CORE_SERVICE_EMAIL/CORE_SERVICE_PASSWORD no están configurados" | |
| ) | |
| return None | |
| cached = _service_token_cache["token"] | |
| if cached and time.time() < _service_token_cache["expires_at"]: | |
| return cached | |
| return _login_service_account() | |
| def _login_service_account() -> str | None: | |
| url = f"{settings.m10_core_url}/auth/login" | |
| payload = {"email": settings.core_service_email, "password": settings.core_service_password} | |
| try: | |
| r = httpx.post(url, json=payload, timeout=settings.http_timeout_seconds) | |
| r.raise_for_status() | |
| token = r.json().get("token") | |
| except Exception as e: | |
| logger.warning("No se pudo autenticar la cuenta de servicio de M6 en el Core: %s", e) | |
| return None | |
| if not token: | |
| return None | |
| try: | |
| exp = jwt.get_unverified_claims(token).get("exp") | |
| except JWTError: | |
| exp = None | |
| _service_token_cache["token"] = token | |
| _service_token_cache["expires_at"] = ( | |
| exp - _SERVICE_TOKEN_EXPIRY_MARGIN_SECONDS if exp else time.time() + 60 | |
| ) | |
| return token | |
| # ─── Mapeo de rol de Core → rol interno de M6 ────────────────────────────── | |
| # El rol del usuario se obtiene una única vez, en el canje SSO | |
| # (`user.roles[].name` de la respuesta de `/auth/sso-exchange` — | |
| # `models.AuthResponse` → `models.User` → `models.Role`, ver | |
| # `documentation/M10_openapi.yaml`). No hay lookup aparte (`GET /roles`) ni | |
| # verificación de JWT del Core por-request: la sesión de M6 es siempre el | |
| # JWT HS256 propio emitido en `app/routers/auth.py`. Este mapeo es la única | |
| # fuente de la verdad de qué rol de Core habilita qué rol interno de M6; | |
| # ajustar acá si cambian los nombres en el Core compartido. | |
| CORE_ROLE_TO_INTERNAL: dict[str, str] = { | |
| "admin_internacion": "ADMINISTRATIVO", | |
| "admin": "ADMINISTRATIVO", # super-admin del Core — a confirmar con el equipo M10 | |
| "Medico": "MEDICO", | |
| "limpieza": "LIMPIEZA", | |
| } | |
| # Si un usuario tiene varios roles mapeados, gana el de mayor alcance. | |
| _ROLE_PRECEDENCE = ("ADMINISTRATIVO", "MEDICO", "LIMPIEZA") | |
| def map_core_roles_to_internal(role_names: list[str]) -> str | None: | |
| """ | |
| Traduce roles de Core al rol interno de M6, con precedencia si el | |
| usuario tiene más de uno mapeado. `None` si ninguno mapea (sin acceso). | |
| """ | |
| mapped = {CORE_ROLE_TO_INTERNAL[name] for name in role_names if name in CORE_ROLE_TO_INTERNAL} | |
| for rol in _ROLE_PRECEDENCE: | |
| if rol in mapped: | |
| return rol | |
| return None | |