Mate11 commited on
Commit
c5aafdb
·
1 Parent(s): d5fcbdc

Auth: integrar login con M10 Core API

Browse files

- POST /api/v1/auth/login delega a Core en modo real; emite JWT propio con rol del perfil del usuario
- Modo mock preservado para desarrollo sin stack completo
- Manejo de errores: 401 si Core rechaza credenciales, 502 si respuesta malformada
- 4 tests nuevos en test_auth.py (64 total, todos pasan)

app/integrations/core.py CHANGED
@@ -1,8 +1,8 @@
1
  """
2
- M10 Core — validación de pacientes.
3
  """
4
  from app.config import settings
5
- from app.integrations._base import _get
6
 
7
 
8
  def validate_patient(paciente_id: int) -> dict | None:
@@ -10,3 +10,16 @@ def validate_patient(paciente_id: int) -> dict | None:
10
  if settings.mock_external_services:
11
  return {"id": paciente_id, "nombre": "Paciente", "apellido": "Mock"}
12
  return _get(f"{settings.m10_core_url}/api/v1/usuarios/{paciente_id}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  """
2
+ M10 Core — validación de pacientes y autenticación.
3
  """
4
  from app.config import settings
5
+ from app.integrations._base import _get, _post
6
 
7
 
8
  def validate_patient(paciente_id: int) -> dict | None:
 
10
  if settings.mock_external_services:
11
  return {"id": paciente_id, "nombre": "Paciente", "apellido": "Mock"}
12
  return _get(f"{settings.m10_core_url}/api/v1/usuarios/{paciente_id}")
13
+
14
+
15
+ def login_core(email: str, password: str) -> dict | None:
16
+ """Autentica en M10. Retorna {"token": ..., "user": {...}} o None."""
17
+ return _post(
18
+ f"{settings.m10_core_url}/auth/login",
19
+ {"email": email, "password": password},
20
+ )
21
+
22
+
23
+ def get_user_core(user_id: int, token: str) -> dict | None:
24
+ """Obtiene perfil del usuario en M10 usando el token de Core."""
25
+ return _get(f"{settings.m10_core_url}/api/v1/usuarios/{user_id}", token=token)
app/main.py CHANGED
@@ -5,14 +5,14 @@ API REST: http://localhost:8006/api/v1
5
 
6
  import logging
7
  from contextlib import asynccontextmanager
8
- from fastapi import FastAPI, Request, status
9
  from fastapi.middleware.cors import CORSMiddleware
10
  from fastapi.responses import JSONResponse
11
 
12
  from app.config import settings
13
- from app.dependencies import create_access_token
14
 
15
  from app.routers import camas, quirofanos, solicitudes, webhooks
 
16
  from app.routers.webhooks import router_turnos
17
 
18
  logger = logging.getLogger(__name__)
@@ -56,6 +56,7 @@ app.add_middleware(
56
 
57
  PREFIX = "/api/v1"
58
 
 
59
  app.include_router(camas.router, prefix=PREFIX)
60
  app.include_router(quirofanos.router, prefix=PREFIX)
61
  app.include_router(solicitudes.router, prefix=PREFIX)
@@ -63,40 +64,6 @@ app.include_router(webhooks.router, prefix=PREFIX)
63
  app.include_router(router_turnos, prefix=PREFIX)
64
 
65
 
66
- # ─── Endpoint de auth local (mock de M10 — solo para desarrollo) ───────────
67
-
68
-
69
- @app.get(
70
- f"{PREFIX}/auth/token",
71
- tags=["Auth (dev)"],
72
- summary="Obtener JWT de desarrollo",
73
- include_in_schema=True,
74
- )
75
- def get_dev_token(usuario: str, password: str):
76
- """
77
- Solo habilitado si ENVIRONMENT=development.
78
- Genera un JWT de prueba. Roles válidos: ADMINISTRATIVO | MEDICO | LIMPIEZA
79
- """
80
- if settings.environment != "development":
81
- return JSONResponse(
82
- status_code=404,
83
- content={"codigo": "RECURSO_NO_ENCONTRADO", "mensaje": "Not Found"},
84
- )
85
-
86
- roles_validos = {"ADMINISTRATIVO", "MEDICO", "LIMPIEZA"}
87
- rol = usuario.upper()
88
- if rol not in roles_validos:
89
- return JSONResponse(
90
- status_code=status.HTTP_401_UNAUTHORIZED,
91
- content={
92
- "codigo": "NO_AUTENTICADO",
93
- "mensaje": f"Rol inválido. Usar: {roles_validos}",
94
- },
95
- )
96
- token = create_access_token(sub="1", rol=rol)
97
- return {"access_token": token, "token_type": "bearer", "rol": rol}
98
-
99
-
100
  # ─── Health check ──────────────────────────────────────────────────────────
101
 
102
 
 
5
 
6
  import logging
7
  from contextlib import asynccontextmanager
8
+ from fastapi import FastAPI, Request
9
  from fastapi.middleware.cors import CORSMiddleware
10
  from fastapi.responses import JSONResponse
11
 
12
  from app.config import settings
 
13
 
14
  from app.routers import camas, quirofanos, solicitudes, webhooks
15
+ from app.routers.auth import router as auth_router
16
  from app.routers.webhooks import router_turnos
17
 
18
  logger = logging.getLogger(__name__)
 
56
 
57
  PREFIX = "/api/v1"
58
 
59
+ app.include_router(auth_router, prefix=PREFIX)
60
  app.include_router(camas.router, prefix=PREFIX)
61
  app.include_router(quirofanos.router, prefix=PREFIX)
62
  app.include_router(solicitudes.router, prefix=PREFIX)
 
64
  app.include_router(router_turnos, prefix=PREFIX)
65
 
66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
  # ─── Health check ──────────────────────────────────────────────────────────
68
 
69
 
app/routers/auth.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+
3
+ from fastapi import APIRouter, HTTPException, status
4
+ from pydantic import BaseModel
5
+
6
+ from app.config import settings
7
+ from app.dependencies import create_access_token
8
+ from app.integrations.core import login_core, get_user_core
9
+
10
+ router = APIRouter(tags=["Auth"])
11
+ logger = logging.getLogger(__name__)
12
+
13
+
14
+ class LoginRequest(BaseModel):
15
+ email: str
16
+ password: str
17
+
18
+
19
+ @router.post("/auth/login")
20
+ def login(body: LoginRequest):
21
+ if settings.mock_external_services:
22
+ token = create_access_token(sub="1", rol="ADMINISTRATIVO")
23
+ return {"access_token": token, "token_type": "bearer"}
24
+
25
+ result = login_core(body.email, body.password)
26
+ if not result:
27
+ raise HTTPException(
28
+ status_code=status.HTTP_401_UNAUTHORIZED,
29
+ detail={"codigo": "NO_AUTENTICADO", "mensaje": "Credenciales inválidas"},
30
+ )
31
+
32
+ core_token = result.get("token")
33
+ user = result.get("user")
34
+ if not core_token or not user or not isinstance(user, dict):
35
+ logger.error("Core API devolvió respuesta malformada en login")
36
+ raise HTTPException(
37
+ status_code=status.HTTP_502_BAD_GATEWAY,
38
+ detail={"codigo": "ERROR_EXTERNO", "mensaje": "Error en servicio de autenticación"},
39
+ )
40
+
41
+ user_id = user.get("id")
42
+ if not user_id:
43
+ logger.error("Core API no devolvió user.id en login")
44
+ raise HTTPException(
45
+ status_code=status.HTTP_502_BAD_GATEWAY,
46
+ detail={"codigo": "ERROR_EXTERNO", "mensaje": "Error en servicio de autenticación"},
47
+ )
48
+
49
+ rol = "ADMINISTRATIVO"
50
+ profile = get_user_core(user_id, core_token)
51
+ if profile:
52
+ roles = profile.get("roles", [])
53
+ if roles and isinstance(roles[0], dict):
54
+ rol = roles[0].get("name", rol)
55
+
56
+ token = create_access_token(sub=str(user_id), rol=rol)
57
+ return {"access_token": token, "token_type": "bearer"}
tests/test_auth.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Tests del router de Auth.
3
+
4
+ Ejercitan el endpoint POST /api/v1/auth/login en modo mock y en modo real,
5
+ mockeando las dependencias externas (login_core, get_user_core, settings).
6
+ """
7
+ from unittest.mock import patch, MagicMock
8
+ from fastapi.testclient import TestClient
9
+
10
+ PREFIX = "/api/v1/auth/login"
11
+
12
+
13
+ # ─── Modo mock (mock_external_services=True) ──────────────────────────────────
14
+
15
+ def test_login_mock_credenciales_validas(client: TestClient):
16
+ """En modo mock, cualquier credencial válida devuelve 200 con access_token."""
17
+ resp = client.post(PREFIX, json={"email": "test@test.com", "password": "123"})
18
+ assert resp.status_code == 200
19
+ data = resp.json()
20
+ assert "access_token" in data
21
+ assert data["token_type"] == "bearer"
22
+
23
+
24
+ def test_login_body_invalido_422(client: TestClient):
25
+ """Body vacío debe fallar con 422 (validación de Pydantic)."""
26
+ resp = client.post(PREFIX, json={})
27
+ assert resp.status_code == 422
28
+
29
+
30
+ # ─── Modo real (mock_external_services=False) ─────────────────────────────────
31
+
32
+ def test_login_real_exitoso(client: TestClient):
33
+ """Modo real: login_core y get_user_core exitosos → 200 con access_token."""
34
+ mock_settings = MagicMock()
35
+ mock_settings.mock_external_services = False
36
+
37
+ core_login_result = {"token": "core_tok", "user": {"id": 42}}
38
+ core_profile_result = {"roles": [{"id": 1, "name": "MEDICO"}]}
39
+
40
+ with patch("app.routers.auth.settings", mock_settings), \
41
+ patch("app.routers.auth.login_core", return_value=core_login_result), \
42
+ patch("app.routers.auth.get_user_core", return_value=core_profile_result):
43
+
44
+ resp = client.post(PREFIX, json={"email": "medico@test.com", "password": "pass"})
45
+
46
+ assert resp.status_code == 200
47
+ assert "access_token" in resp.json()
48
+
49
+
50
+ def test_login_real_core_falla_401(client: TestClient):
51
+ """Modo real: login_core retorna None → 401 con credenciales inválidas."""
52
+ mock_settings = MagicMock()
53
+ mock_settings.mock_external_services = False
54
+
55
+ with patch("app.routers.auth.settings", mock_settings), \
56
+ patch("app.routers.auth.login_core", return_value=None):
57
+
58
+ resp = client.post(PREFIX, json={"email": "nadie@test.com", "password": "wrong"})
59
+
60
+ assert resp.status_code == 401