feat(audit): implement institutional audit logging for logins and system operations v3.4.8
This commit is contained in:
@@ -6,7 +6,7 @@ from flask_babel import Babel, gettext as _
|
||||
from config.config import Config
|
||||
|
||||
# Initialize extensions
|
||||
__version__ = "3.4.7"
|
||||
__version__ = "3.4.8"
|
||||
db = SQLAlchemy()
|
||||
migrate = Migrate()
|
||||
cors = CORS()
|
||||
|
||||
@@ -23,3 +23,19 @@ class AuditLog(db.Model):
|
||||
|
||||
def __repr__(self):
|
||||
return f"<AuditLog #{self.id} {self.action} on {self.module} by {self.user_email or 'System'}>"
|
||||
|
||||
def to_dict(self):
|
||||
"""Serializa el registro de auditoría a diccionario JSON."""
|
||||
return {
|
||||
'id': self.id,
|
||||
'user_id': self.user_id,
|
||||
'user_email': self.user_email,
|
||||
'action': self.action,
|
||||
'module': self.module,
|
||||
'entity_id': self.entity_id,
|
||||
'details': self.details,
|
||||
'ip_address': self.ip_address,
|
||||
'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S') if self.created_at else None,
|
||||
'created_at_iso': self.created_at.isoformat() if self.created_at else None
|
||||
}
|
||||
|
||||
|
||||
@@ -12,6 +12,8 @@ from app.models.reservation import Reservation, ReservationStatus
|
||||
from app.models.academic_term import AcademicTerm
|
||||
from app.models.milestone import MilestoneType, AcademicMilestone
|
||||
from app.models.audit_log import AuditLog
|
||||
from app.services.audit_service import AuditService
|
||||
from sqlalchemy import or_
|
||||
from app.constants.document_types import DOCUMENT_TYPES, validate_document, format_document
|
||||
from app.services.enrollment_service import EnrollmentService
|
||||
from app.services.gradebook_service import GradebookService
|
||||
@@ -2556,6 +2558,14 @@ def create_building():
|
||||
db.session.add(building)
|
||||
db.session.commit()
|
||||
|
||||
AuditService.log(
|
||||
action='CREATE',
|
||||
module='buildings',
|
||||
entity_id=building.id,
|
||||
user=g.jwt_user,
|
||||
details=f"Nueva sede/edificio creado: '{building.name}' (Código: {building.code or 'S/C'}, Pisos: {building.floors})"
|
||||
)
|
||||
|
||||
return jsonify({
|
||||
'status': 'success',
|
||||
'message': f'Edificio "{name}" creado con éxito.',
|
||||
@@ -2607,6 +2617,14 @@ def update_building(id):
|
||||
|
||||
db.session.commit()
|
||||
|
||||
AuditService.log(
|
||||
action='UPDATE',
|
||||
module='buildings',
|
||||
entity_id=building.id,
|
||||
user=g.jwt_user,
|
||||
details=f"Edificio/sede #{building.id} ('{building.name}') actualizado. Pisos: {building.floors}, Código: {building.code}"
|
||||
)
|
||||
|
||||
return jsonify({
|
||||
'status': 'success',
|
||||
'message': f'Edificio "{building.name}" actualizado con éxito.',
|
||||
@@ -2626,6 +2644,14 @@ def toggle_building(id):
|
||||
building.updated_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
|
||||
AuditService.log(
|
||||
action='TOGGLE',
|
||||
module='buildings',
|
||||
entity_id=building.id,
|
||||
user=g.jwt_user,
|
||||
details=f"Edificio '{building.name}' {'activado' if building.is_active else 'desactivado'}"
|
||||
)
|
||||
|
||||
return jsonify({
|
||||
'status': 'success',
|
||||
'message': f'Edificio "{building.name}" {"activado" if building.is_active else "desactivado"} exitosamente.',
|
||||
@@ -2651,12 +2677,21 @@ def delete_building(id):
|
||||
'message': f'No se puede eliminar el edificio "{building.name}" porque tiene {count} aulas asociadas.'
|
||||
}), 409
|
||||
|
||||
b_name = building.name
|
||||
db.session.delete(building)
|
||||
db.session.commit()
|
||||
|
||||
AuditService.log(
|
||||
action='DELETE',
|
||||
module='buildings',
|
||||
entity_id=id,
|
||||
user=g.jwt_user,
|
||||
details=f"Edificio/sede #{id} ('{b_name}') eliminado permanentemente"
|
||||
)
|
||||
|
||||
return jsonify({
|
||||
'status': 'success',
|
||||
'message': f'Edificio "{building.name}" eliminado correctamente.'
|
||||
'message': f'Edificio "{b_name}" eliminado correctamente.'
|
||||
}), 200
|
||||
|
||||
|
||||
@@ -2791,3 +2826,83 @@ def reset_entire_system():
|
||||
'message': f'Error durante la reinicialización de la base de datos: {str(e)}'
|
||||
}), 500
|
||||
|
||||
|
||||
# ---------------------------------------------------------
|
||||
# REGISTRO DE AUDITORÍA INSTITUCIONAL RESTful
|
||||
# ---------------------------------------------------------
|
||||
|
||||
@api_admin_bp.route('/audit-logs', methods=['GET'])
|
||||
@api_admin_bp.route('/audit_logs', methods=['GET'])
|
||||
@jwt_required
|
||||
def get_audit_logs():
|
||||
"""
|
||||
Endpoint RESTful para consultar la bitácora inmutable de auditoría institucional.
|
||||
Soporta paginación, búsqueda multi-campo y filtrado por módulo y acción.
|
||||
"""
|
||||
page = request.args.get('page', 1, type=int)
|
||||
per_page = min(request.args.get('per_page', 20, type=int), 100)
|
||||
module_filter = request.args.get('module', '').strip().lower()
|
||||
action_filter = request.args.get('action', '').strip().upper()
|
||||
search = request.args.get('search', '').strip()
|
||||
|
||||
query = AuditLog.query
|
||||
|
||||
if module_filter:
|
||||
query = query.filter(AuditLog.module == module_filter)
|
||||
if action_filter:
|
||||
query = query.filter(AuditLog.action == action_filter)
|
||||
if search:
|
||||
query = query.filter(
|
||||
or_(
|
||||
AuditLog.user_email.ilike(f'%{search}%'),
|
||||
AuditLog.details.ilike(f'%{search}%'),
|
||||
AuditLog.ip_address.ilike(f'%{search}%'),
|
||||
AuditLog.action.ilike(f'%{search}%'),
|
||||
AuditLog.module.ilike(f'%{search}%')
|
||||
)
|
||||
)
|
||||
|
||||
pagination = query.order_by(AuditLog.created_at.desc()).paginate(
|
||||
page=page, per_page=per_page, error_out=False
|
||||
)
|
||||
|
||||
modules_tuples = db.session.query(AuditLog.module).distinct().all()
|
||||
actions_tuples = db.session.query(AuditLog.action).distinct().all()
|
||||
|
||||
modules = sorted(list(set([r[0].lower() for r in modules_tuples if r[0]])))
|
||||
actions = sorted(list(set([r[0].upper() for r in actions_tuples if r[0]])))
|
||||
|
||||
default_modules = ['auth', 'reservations', 'classrooms', 'buildings', 'academic', 'optimizer', 'users', 'admin']
|
||||
for m in default_modules:
|
||||
if m not in modules:
|
||||
modules.append(m)
|
||||
|
||||
default_actions = [
|
||||
'LOGIN', 'LOGIN_FAILED', 'LOGIN_BLOCKED', 'LOGIN_GOOGLE', 'LOGIN_MOODLE', 'LOGOUT',
|
||||
'PASSWORD_CHANGE', 'IMPERSONATE_START', 'IMPERSONATE_END',
|
||||
'CREATE', 'UPDATE', 'DELETE', 'CONFIRM', 'CANCEL', 'TOGGLE',
|
||||
'OPTIMIZE_RUN', 'OPTIMIZE_APPLY', 'SYSTEM_RESET'
|
||||
]
|
||||
for a in default_actions:
|
||||
if a not in actions:
|
||||
actions.append(a)
|
||||
|
||||
return jsonify({
|
||||
'status': 'success',
|
||||
'logs': [log.to_dict() for log in pagination.items],
|
||||
'pagination': {
|
||||
'page': pagination.page,
|
||||
'per_page': pagination.per_page,
|
||||
'total': pagination.total,
|
||||
'pages': pagination.pages or 1,
|
||||
'has_prev': pagination.has_prev,
|
||||
'has_next': pagination.has_next
|
||||
},
|
||||
'modules': sorted(modules),
|
||||
'actions': sorted(actions),
|
||||
'current_module': module_filter,
|
||||
'current_action': action_filter,
|
||||
'search': search
|
||||
}), 200
|
||||
|
||||
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -4,6 +4,7 @@ from pydantic import ValidationError
|
||||
from app import db
|
||||
from app.models.classroom import Classroom
|
||||
from app.services.classroom_service import ClassroomService
|
||||
from app.services.audit_service import AuditService
|
||||
from app.schemas.classroom_dto import ClassroomCreateDTO, ClassroomUpdateDTO, ClassroomResponseDTO
|
||||
from app.utils.jwt_decorators import jwt_required, jwt_role_required
|
||||
|
||||
@@ -80,6 +81,13 @@ def create_classroom():
|
||||
|
||||
try:
|
||||
classroom = classroom_service.create_classroom(dto)
|
||||
AuditService.log(
|
||||
action='CREATE',
|
||||
module='classrooms',
|
||||
entity_id=classroom.id,
|
||||
user=g.jwt_user,
|
||||
details=f"Nueva aula creada: {classroom.code} en {classroom.building} (Piso {classroom.floor}, Capacidad: {classroom.capacity})"
|
||||
)
|
||||
return jsonify({
|
||||
'message': 'Aula creada exitosamente.',
|
||||
'id': classroom.id,
|
||||
@@ -101,6 +109,13 @@ def update_classroom(classroom_id: int):
|
||||
|
||||
try:
|
||||
classroom = classroom_service.update_classroom(classroom_id, dto)
|
||||
AuditService.log(
|
||||
action='UPDATE',
|
||||
module='classrooms',
|
||||
entity_id=classroom.id,
|
||||
user=g.jwt_user,
|
||||
details=f"Aula #{classroom.id} ({classroom.code}) actualizada. Capacidad: {classroom.capacity}, Piso: {classroom.floor}"
|
||||
)
|
||||
return jsonify({
|
||||
'message': 'Aula actualizada exitosamente.',
|
||||
'id': classroom.id,
|
||||
@@ -118,6 +133,13 @@ def delete_classroom(classroom_id: int):
|
||||
if not deleted:
|
||||
return jsonify({'error': 'NotFound', 'message': f'Aula {classroom_id} no encontrada.'}), 404
|
||||
|
||||
AuditService.log(
|
||||
action='DELETE',
|
||||
module='classrooms',
|
||||
entity_id=classroom_id,
|
||||
user=g.jwt_user,
|
||||
details=f"Aula #{classroom_id} eliminada/desactivada del sistema"
|
||||
)
|
||||
return jsonify({'message': f'Aula {classroom_id} eliminada/desactivada correctamente.'}), 200
|
||||
|
||||
@api_classrooms_bp.route('/<int:classroom_id>/toggle', methods=['POST'])
|
||||
@@ -127,6 +149,13 @@ def toggle_classroom(classroom_id: int):
|
||||
classroom = Classroom.query.get_or_404(classroom_id)
|
||||
classroom.is_active = not classroom.is_active
|
||||
db.session.commit()
|
||||
AuditService.log(
|
||||
action='TOGGLE',
|
||||
module='classrooms',
|
||||
entity_id=classroom.id,
|
||||
user=g.jwt_user,
|
||||
details=f"Aula {classroom.code} {'activada' if classroom.is_active else 'desactivada'}"
|
||||
)
|
||||
return jsonify({
|
||||
'status': 'success',
|
||||
'id': classroom.id,
|
||||
|
||||
@@ -7,7 +7,7 @@ OPENAPI_SPEC = {
|
||||
"info": {
|
||||
"title": "Edu-Space REST API",
|
||||
"description": "Enterprise Academic & Physical Space Management REST API with JWT Authentication and Role-Based Access Control.",
|
||||
"version": "3.4.7"
|
||||
"version": "3.4.8"
|
||||
},
|
||||
"servers": [
|
||||
{
|
||||
|
||||
@@ -5,6 +5,7 @@ from pydantic import ValidationError
|
||||
from app import db
|
||||
from app.models.reservation import Reservation
|
||||
from app.services.reservation_service import ReservationService
|
||||
from app.services.audit_service import AuditService
|
||||
from app.schemas.reservation_dto import ReservationCreateDTO, ReservationUpdateDTO
|
||||
from app.utils.jwt_decorators import jwt_required, jwt_role_required
|
||||
|
||||
@@ -187,6 +188,13 @@ def create_reservation():
|
||||
|
||||
try:
|
||||
reservation = reservation_service.create_reservation(dto)
|
||||
AuditService.log(
|
||||
action='CREATE',
|
||||
module='reservations',
|
||||
entity_id=reservation.id,
|
||||
user=g.jwt_user,
|
||||
details=f"Nueva reserva creada #{reservation.id} en aula ID {reservation.classroom_id} ({reservation.start_time.strftime('%Y-%m-%d %H:%M')} a {reservation.end_time.strftime('%H:%M')}) - Motivo: {reservation.purpose}"
|
||||
)
|
||||
return jsonify({
|
||||
'message': 'Reserva creada exitosamente.',
|
||||
'id': reservation.id,
|
||||
@@ -210,6 +218,13 @@ def update_reservation(reservation_id: int):
|
||||
|
||||
try:
|
||||
reservation = reservation_service.update_reservation(reservation_id, dto)
|
||||
AuditService.log(
|
||||
action='UPDATE',
|
||||
module='reservations',
|
||||
entity_id=reservation.id,
|
||||
user=g.jwt_user,
|
||||
details=f"Reserva #{reservation.id} modificada ({reservation.start_time.strftime('%Y-%m-%d %H:%M')} a {reservation.end_time.strftime('%H:%M')}) - Estado: {reservation.status}"
|
||||
)
|
||||
return jsonify({
|
||||
'message': 'Reserva actualizada exitosamente.',
|
||||
'id': reservation.id,
|
||||
@@ -231,12 +246,26 @@ def cancel_reservation(reservation_id: int):
|
||||
return jsonify({'error': 'NotFound', 'message': f'Reserva {reservation_id} no encontrada.'}), 404
|
||||
db.session.delete(res)
|
||||
db.session.commit()
|
||||
AuditService.log(
|
||||
action='DELETE',
|
||||
module='reservations',
|
||||
entity_id=reservation_id,
|
||||
user=g.jwt_user,
|
||||
details=f"Reserva #{reservation_id} eliminada permanentemente"
|
||||
)
|
||||
return jsonify({'message': f'Reserva {reservation_id} eliminada permanentemente.'}), 200
|
||||
|
||||
cancelled = reservation_service.cancel_reservation(reservation_id)
|
||||
if not cancelled:
|
||||
return jsonify({'error': 'NotFound', 'message': f'Reserva {reservation_id} no encontrada.'}), 404
|
||||
|
||||
AuditService.log(
|
||||
action='CANCEL',
|
||||
module='reservations',
|
||||
entity_id=reservation_id,
|
||||
user=g.jwt_user,
|
||||
details=f"Reserva #{reservation_id} cancelada"
|
||||
)
|
||||
return jsonify({'message': f'Reserva {reservation_id} cancelada correctamente.'}), 200
|
||||
|
||||
@api_reservations_bp.route('/<int:reservation_id>/delete', methods=['POST'])
|
||||
@@ -248,6 +277,13 @@ def delete_reservation_post(reservation_id: int):
|
||||
return jsonify({'error': 'NotFound', 'message': f'Reserva {reservation_id} no encontrada.'}), 404
|
||||
db.session.delete(res)
|
||||
db.session.commit()
|
||||
AuditService.log(
|
||||
action='DELETE',
|
||||
module='reservations',
|
||||
entity_id=reservation_id,
|
||||
user=g.jwt_user,
|
||||
details=f"Reserva #{reservation_id} eliminada permanentemente"
|
||||
)
|
||||
return jsonify({'message': f'Reserva {reservation_id} eliminada permanentemente.'}), 200
|
||||
|
||||
@api_reservations_bp.route('/<int:reservation_id>/cancel', methods=['POST'])
|
||||
@@ -258,6 +294,13 @@ def cancel_reservation_post(reservation_id: int):
|
||||
if not cancelled:
|
||||
return jsonify({'error': 'NotFound', 'message': f'Reserva {reservation_id} no encontrada.'}), 404
|
||||
|
||||
AuditService.log(
|
||||
action='CANCEL',
|
||||
module='reservations',
|
||||
entity_id=reservation_id,
|
||||
user=g.jwt_user,
|
||||
details=f"Reserva #{reservation_id} cancelada"
|
||||
)
|
||||
return jsonify({'message': f'Reserva {reservation_id} cancelada correctamente.'}), 200
|
||||
|
||||
@api_reservations_bp.route('/<int:reservation_id>/confirm', methods=['POST'])
|
||||
@@ -268,6 +311,13 @@ def confirm_reservation(reservation_id: int):
|
||||
if not confirmed:
|
||||
return jsonify({'error': 'NotFound', 'message': f'Reserva {reservation_id} no encontrada.'}), 404
|
||||
|
||||
AuditService.log(
|
||||
action='CONFIRM',
|
||||
module='reservations',
|
||||
entity_id=reservation_id,
|
||||
user=g.jwt_user,
|
||||
details=f"Reserva #{reservation_id} confirmada oficialmente"
|
||||
)
|
||||
return jsonify({'message': f'Reserva {reservation_id} confirmada correctamente.'}), 200
|
||||
|
||||
@api_reservations_bp.route('/check-conflicts', methods=['POST'])
|
||||
|
||||
@@ -3,6 +3,7 @@ from datetime import datetime, timedelta
|
||||
from app.models.genetic_algorithm import ReservationOptimizer
|
||||
from app.models.reservation import Reservation, ReservationStatus
|
||||
from app import db
|
||||
from app.services.audit_service import AuditService
|
||||
from app.utils.jwt_decorators import jwt_required
|
||||
|
||||
genetic_bp = Blueprint('genetic_algorithm', __name__, url_prefix='/api/genetic')
|
||||
@@ -78,6 +79,13 @@ def optimize_reservations():
|
||||
start_date=start_date,
|
||||
end_date=end_date
|
||||
)
|
||||
|
||||
AuditService.log(
|
||||
action='OPTIMIZE_RUN',
|
||||
module='optimizer',
|
||||
user=g.jwt_user,
|
||||
details=f"Ejecución de algoritmo genético para {len(commission_ids)} comisiones. Fitness: {result.get('fitness_score', 0)}% (Asignadas: {len(result.get('assigned_reservations', []))})"
|
||||
)
|
||||
|
||||
return jsonify({
|
||||
'success': True,
|
||||
@@ -117,6 +125,13 @@ def apply_optimization():
|
||||
# Initialize optimizer and apply reservations
|
||||
optimizer = ReservationOptimizer()
|
||||
applied_reservations = optimizer.apply_optimized_reservations(reservations_data)
|
||||
|
||||
AuditService.log(
|
||||
action='OPTIMIZE_APPLY',
|
||||
module='optimizer',
|
||||
user=g.jwt_user,
|
||||
details=f"Consolidación de optimizador genético: {len(applied_reservations)} reservas aplicadas en base de datos."
|
||||
)
|
||||
|
||||
return jsonify({
|
||||
'success': True,
|
||||
|
||||
@@ -12,19 +12,18 @@ class AuditService:
|
||||
@staticmethod
|
||||
def log(action: str, module: str, entity_id: Optional[int] = None,
|
||||
details: Optional[Any] = None, user: Optional[User] = None,
|
||||
ip_address: Optional[str] = None) -> AuditLog:
|
||||
ip_address: Optional[str] = None,
|
||||
user_id: Optional[int] = None,
|
||||
user_email: Optional[str] = None) -> AuditLog:
|
||||
"""
|
||||
Registra un evento de auditoría de forma segura, infiriendo el usuario e IP
|
||||
desde el contexto actual de la petición si no se especifican.
|
||||
"""
|
||||
user_id = None
|
||||
user_email = None
|
||||
|
||||
# 1. Determinar usuario actuante
|
||||
if user:
|
||||
user_id = user.id
|
||||
user_email = user.email
|
||||
elif has_request_context():
|
||||
elif not user_id and not user_email and has_request_context():
|
||||
if hasattr(g, 'jwt_user') and g.jwt_user:
|
||||
user_id = g.jwt_user.id
|
||||
user_email = g.jwt_user.email
|
||||
|
||||
Reference in New Issue
Block a user