feat: login de emergencia admin en /adm/login y despliegue por defecto de auth unico (v3.8.5)
This commit is contained in:
@@ -7,7 +7,7 @@ from typing import Any
|
||||
from database import db, get_db, engine, SessionLocal, session
|
||||
from config.config import Config
|
||||
|
||||
__version__ = "3.8.4"
|
||||
__version__ = "3.8.5"
|
||||
|
||||
class DummyContext:
|
||||
def __enter__(self):
|
||||
|
||||
@@ -121,6 +121,74 @@ def login(payload: LoginRequest, response: Response):
|
||||
}
|
||||
|
||||
|
||||
@auth_router.post("/adm-login")
|
||||
def adm_login(payload: LoginRequest, response: Response):
|
||||
"""Inicio de sesión administrativo de emergencia/contingencia."""
|
||||
user = user_service.authenticate(payload.email, payload.password)
|
||||
if not user:
|
||||
AuditService.log(
|
||||
action='ADMIN_EMERGENCY_LOGIN_FAILED',
|
||||
module='auth',
|
||||
user_email=payload.email,
|
||||
details=f"Intento fallido en consola de emergencia ADMIN para {payload.email}."
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Credenciales de acceso incorrectas o cuenta inactiva."
|
||||
)
|
||||
|
||||
is_admin = user.is_admin() or getattr(user, 'role', '').upper() == 'ADMIN'
|
||||
if not is_admin:
|
||||
AuditService.log(
|
||||
action='ADMIN_EMERGENCY_LOGIN_DENIED',
|
||||
module='auth',
|
||||
user=user,
|
||||
entity_id=user.id,
|
||||
details=f"Usuario sin privilegios de administrador ({user.email}) intentó acceder por consola de emergencia."
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Acceso denegado. Esta consola de emergencia está reservada exclusivamente a administradores del sistema."
|
||||
)
|
||||
|
||||
AuditService.log(
|
||||
action='ADMIN_EMERGENCY_LOGIN_SUCCESS',
|
||||
module='auth',
|
||||
user=user,
|
||||
entity_id=user.id,
|
||||
details=f"Acceso de emergencia exitoso a consola administrativa - Usuario: {user.email}"
|
||||
)
|
||||
|
||||
tokens = JWTService.generate_tokens(user)
|
||||
profile = user_service.get_profile_data(user)
|
||||
|
||||
response.set_cookie(
|
||||
key="access_token",
|
||||
value=tokens["access_token"],
|
||||
httponly=True,
|
||||
samesite="lax",
|
||||
path="/"
|
||||
)
|
||||
response.set_cookie(
|
||||
key="refresh_token",
|
||||
value=tokens["refresh_token"],
|
||||
httponly=True,
|
||||
samesite="lax",
|
||||
max_age=7 * 24 * 3600,
|
||||
path="/api/v1/auth/refresh"
|
||||
)
|
||||
|
||||
return {
|
||||
'status': 'success',
|
||||
'access_token': tokens['access_token'],
|
||||
'refresh_token': tokens['refresh_token'],
|
||||
'token_type': tokens['token_type'],
|
||||
'expires_in': tokens['expires_in'],
|
||||
'user': profile
|
||||
}
|
||||
|
||||
|
||||
|
||||
@auth_router.post("/google")
|
||||
def google_auth(payload: GoogleAuthRequest, response: Response):
|
||||
"""Inicio de sesión delegado institucional Google OAuth 2.0."""
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@ from setuptools import setup, find_packages
|
||||
|
||||
setup(
|
||||
name="edu-space-admin",
|
||||
version="3.8.4",
|
||||
version="3.8.5",
|
||||
description="Administrative interface for Edu-Space Classroom Management System (FastAPI ASGI Core)",
|
||||
author="Edu-Space Development Team",
|
||||
author_email="admin@edu-space.com",
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
"""
|
||||
Tests for Admin Emergency Login endpoint (/api/v1/auth/adm-login).
|
||||
"""
|
||||
from fastapi.testclient import TestClient
|
||||
from werkzeug.security import generate_password_hash
|
||||
from main import app
|
||||
from app.models.user import User
|
||||
|
||||
|
||||
def test_adm_login_success(init_database):
|
||||
"""Admin credentials allow successful login in emergency endpoint."""
|
||||
client = TestClient(app)
|
||||
admin = User(
|
||||
email="emergency.admin@unicaba.edu.ar",
|
||||
name="Emergency Administrator",
|
||||
password_hash=generate_password_hash("AdminPass123!"),
|
||||
role="ADMIN",
|
||||
is_active=True
|
||||
)
|
||||
init_database.session.add(admin)
|
||||
init_database.session.commit()
|
||||
|
||||
res = client.post('/api/v1/auth/adm-login', json={
|
||||
'email': 'emergency.admin@unicaba.edu.ar',
|
||||
'password': 'AdminPass123!'
|
||||
})
|
||||
assert res.status_code == 200
|
||||
data = res.json()
|
||||
assert data['status'] == 'success'
|
||||
assert 'access_token' in data
|
||||
assert 'refresh_token' in data
|
||||
assert data['user']['role'].upper() == 'ADMIN'
|
||||
assert 'access_token' in res.cookies
|
||||
|
||||
|
||||
def test_adm_login_invalid_credentials(init_database):
|
||||
"""Wrong credentials return 401 Unauthorized."""
|
||||
client = TestClient(app)
|
||||
admin = User(
|
||||
email="admin.wrongpass@unicaba.edu.ar",
|
||||
name="Admin Wrong Pass",
|
||||
password_hash=generate_password_hash("CorrectPass123!"),
|
||||
role="ADMIN",
|
||||
is_active=True
|
||||
)
|
||||
init_database.session.add(admin)
|
||||
init_database.session.commit()
|
||||
|
||||
res = client.post('/api/v1/auth/adm-login', json={
|
||||
'email': 'admin.wrongpass@unicaba.edu.ar',
|
||||
'password': 'BadPassword!'
|
||||
})
|
||||
assert res.status_code == 401
|
||||
assert "incorrectas" in res.json()['detail'].lower()
|
||||
|
||||
|
||||
def test_adm_login_denied_for_regular_user(init_database):
|
||||
"""Regular users (Docente/Estudiante) cannot use emergency admin login, receiving 403."""
|
||||
client = TestClient(app)
|
||||
teacher = User(
|
||||
email="profesor.test@unicaba.edu.ar",
|
||||
name="Profesor Test",
|
||||
password_hash=generate_password_hash("DocentePass123!"),
|
||||
role="DOCENTE",
|
||||
is_active=True
|
||||
)
|
||||
init_database.session.add(teacher)
|
||||
init_database.session.commit()
|
||||
|
||||
res = client.post('/api/v1/auth/adm-login', json={
|
||||
'email': 'profesor.test@unicaba.edu.ar',
|
||||
'password': 'DocentePass123!'
|
||||
})
|
||||
assert res.status_code == 403
|
||||
assert "exclusivamente a administradores" in res.json()['detail'].lower()
|
||||
|
||||
|
||||
def test_adm_login_inactive_user(init_database):
|
||||
"""Inactive admin cannot log in, receiving 401."""
|
||||
client = TestClient(app)
|
||||
admin = User(
|
||||
email="inactive.admin@unicaba.edu.ar",
|
||||
name="Inactive Admin",
|
||||
password_hash=generate_password_hash("Pass123!"),
|
||||
role="ADMIN",
|
||||
is_active=False
|
||||
)
|
||||
init_database.session.add(admin)
|
||||
init_database.session.commit()
|
||||
|
||||
res = client.post('/api/v1/auth/adm-login', json={
|
||||
'email': 'inactive.admin@unicaba.edu.ar',
|
||||
'password': 'Pass123!'
|
||||
})
|
||||
assert res.status_code == 401
|
||||
Reference in New Issue
Block a user