feat(audit): implement institutional audit logging for logins and system operations v3.4.8
This commit is contained in:
@@ -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
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user