feat(audit): implement institutional audit logging for logins and system operations v3.4.8

This commit is contained in:
2026-10-09 09:53:54 -03:00
parent 47c21dd25a
commit 1edd81516a
19 changed files with 795 additions and 79 deletions
+87
View File
@@ -20,6 +20,7 @@ from app.services.user_service import UserService
from app.services.jwt_service import JWTService
from app.services.cache_service import cache_service
from app.services.moodle_client import moodle_client
from app.services.audit_service import AuditService
from app.schemas.auth_dto import LoginDTO, RefreshTokenDTO
from app.utils.jwt_decorators import jwt_required
@@ -69,6 +70,12 @@ def login():
user = user_service.authenticate(dto.email, dto.password)
if not user:
AuditService.log(
action='LOGIN_FAILED',
module='auth',
user_email=dto.email,
details=f"Intento de inicio de sesión fallido para {dto.email}. Credenciales incorrectas o cuenta inactiva."
)
return jsonify({
'error': 'Unauthorized',
'message': 'Credenciales de acceso incorrectas o cuenta inactiva.'
@@ -76,11 +83,26 @@ def login():
is_admin = user.is_admin() or getattr(user, 'role', '').upper() == 'ADMIN'
if not local_enabled and not is_admin:
AuditService.log(
action='LOGIN_BLOCKED',
module='auth',
user=user,
entity_id=user.id,
details=f"Acceso local con contraseña bloqueado para {user.email}. Método deshabilitado por administración."
)
return jsonify({
'error': 'Forbidden',
'message': 'El acceso local con contraseña está deshabilitado por el administrador. Inicie sesión mediante Google OAuth o Moodle.'
}), 403
AuditService.log(
action='LOGIN',
module='auth',
user=user,
entity_id=user.id,
details=f"Inicio de sesión exitoso (Autenticación Local) - Rol: {user.role}"
)
tokens = JWTService.generate_tokens(user)
profile = user_service.get_profile_data(user)
@@ -130,6 +152,12 @@ def google_auth():
if allowed_domains and domain.lower() not in allowed_domains:
logger.warning(f"[GoogleAuth] Access denied for {email}: domain {domain} not in {allowed_domains}")
AuditService.log(
action='LOGIN_FAILED',
module='auth',
user_email=email,
details=f"Acceso Google OAuth denegado: dominio @{domain} no autorizado para {email}."
)
return jsonify({
'error': 'Forbidden',
'message': f'Acceso denegado. El dominio @{domain} no está autorizado en esta institución.'
@@ -159,8 +187,23 @@ def google_auth():
logger.info(f"[GoogleAuth] Created new local user for {email} with role Docente.")
if not user.is_active:
AuditService.log(
action='LOGIN_FAILED',
module='auth',
user=user,
entity_id=user.id,
details=f"Acceso Google OAuth denegado: cuenta institucional desactivada para {email}."
)
return jsonify({'error': 'Unauthorized', 'message': 'Su cuenta se encuentra inactiva. Contacte a Bedelía.'}), 401
AuditService.log(
action='LOGIN_GOOGLE',
module='auth',
user=user,
entity_id=user.id,
details=f"Inicio de sesión exitoso (Google OAuth SSO) - Rol: {user.role}"
)
tokens = JWTService.generate_tokens(user)
profile = user_service.get_profile_data(user)
@@ -220,6 +263,12 @@ def moodle_auth():
if 'error' in res_data or 'token' not in res_data:
err_msg = res_data.get('error', 'Credenciales inválidas en Moodle.')
AuditService.log(
action='LOGIN_FAILED',
module='auth',
user_email=f"{username}@unicaba.edu.ar",
details=f"Intento de autenticación Moodle fallido para '{username}': {err_msg}"
)
return jsonify({'error': 'Unauthorized', 'message': f'Moodle: {err_msg}'}), 401
moodle_user_token = res_data['token']
@@ -265,8 +314,23 @@ def moodle_auth():
logger.info(f"[MoodleAuth] Created new local user for Moodle username '{username}' with role '{role_name}'.")
if not user.is_active:
AuditService.log(
action='LOGIN_FAILED',
module='auth',
user=user,
entity_id=user.id,
details=f"Inicio de sesión Moodle denegado: cuenta institucional desactivada para {username}."
)
return jsonify({'error': 'Unauthorized', 'message': 'Su cuenta en Edu-Space está desactivada.'}), 401
AuditService.log(
action='LOGIN_MOODLE',
module='auth',
user=user,
entity_id=user.id,
details=f"Inicio de sesión exitoso (Moodle Delegado) - Usuario: {username}, Rol: {user.role}"
)
tokens = JWTService.generate_tokens(user)
profile = user_service.get_profile_data(user)
@@ -336,6 +400,14 @@ def logout():
"""
Session logout: revokes active access token and clears cookies.
"""
if g.jwt_user:
AuditService.log(
action='LOGOUT',
module='auth',
user=g.jwt_user,
entity_id=g.jwt_user.id,
details=f"Cierre de sesión seguro de {g.jwt_user.email}"
)
JWTService.revoke_token(g.jwt_token)
resp = make_response(jsonify({'message': 'Sesión finalizada y token revocado exitosamente.'}), 200)
resp.delete_cookie('refresh_token', path='/api/v1/auth/refresh')
@@ -375,6 +447,13 @@ def change_password():
user = g.jwt_user
if not user.check_password(current_password):
AuditService.log(
action='PASSWORD_FAILED',
module='auth',
user=user,
entity_id=user.id,
details="Intento fallido de cambio de contraseña: la contraseña actual no coincide."
)
return jsonify({
'error': 'Unauthorized',
'message': 'La contraseña actual ingresada es incorrecta.'
@@ -383,6 +462,14 @@ def change_password():
user.set_password(new_password)
db.session.commit()
AuditService.log(
action='PASSWORD_CHANGE',
module='auth',
user=user,
entity_id=user.id,
details="Cambio de contraseña institucional completado exitosamente."
)
logger.info(f"[Auth] Password successfully updated for user {user.email}")
return jsonify({
'status': 'success',