feat(roadmap): implementar Sprints 1, 2 y 3 (MVC, Stateless JWT API y Spring Security)

This commit is contained in:
Carlos Tello
2026-09-05 01:46:57 -03:00
parent fa878cb0d5
commit 69b8b7ccef
34 changed files with 1750 additions and 21 deletions
+10
View File
@@ -0,0 +1,10 @@
"""Paquete de rutas API RESTful (v1) con soporte Stateless JWT."""
from app.routes.api.auth import api_auth_bp
from app.routes.api.classrooms import api_classrooms_bp
from app.routes.api.reservations import api_reservations_bp
__all__ = [
'api_auth_bp',
'api_classrooms_bp',
'api_reservations_bp'
]
+109
View File
@@ -0,0 +1,109 @@
from flask import Blueprint, request, jsonify, g, make_response
from pydantic import ValidationError
import jwt
from app.services.user_service import UserService
from app.services.jwt_service import JWTService
from app.schemas.auth_dto import LoginDTO, RefreshTokenDTO
from app.utils.jwt_decorators import jwt_required
api_auth_bp = Blueprint('api_auth', __name__, url_prefix='/api/v1/auth')
user_service = UserService()
@api_auth_bp.route('/login', methods=['POST'])
def login():
"""
Endpoint de autenticación para obtener par de tokens (Access + Refresh).
"""
data = request.get_json(silent=True) or {}
try:
dto = LoginDTO(**data)
except ValidationError as e:
return jsonify({'error': 'ValidationError', 'details': e.errors()}), 400
user = user_service.authenticate(dto.email, dto.password)
if not user:
return jsonify({
'error': 'Unauthorized',
'message': 'Credenciales de acceso incorrectas o cuenta inactiva.'
}), 401
tokens = JWTService.generate_tokens(user)
profile = user_service.get_profile_data(user)
response_data = {
'access_token': tokens['access_token'],
'refresh_token': tokens['refresh_token'],
'token_type': tokens['token_type'],
'expires_in': tokens['expires_in'],
'user': profile
}
resp = make_response(jsonify(response_data), 200)
# Almacenar refresh token en cookie segura HttpOnly
resp.set_cookie(
'refresh_token',
tokens['refresh_token'],
httponly=True,
samesite='Lax',
max_age=7 * 24 * 3600,
path='/api/v1/auth/refresh'
)
return resp
@api_auth_bp.route('/refresh', methods=['POST'])
def refresh():
"""
Renovación silenciosa del Access Token utilizando el Refresh Token.
"""
data = request.get_json(silent=True) or {}
refresh_token = data.get('refresh_token') or request.cookies.get('refresh_token')
if not refresh_token:
return jsonify({
'error': 'BadRequest',
'message': 'Refresh token no suministrado en el cuerpo ni en cookies.'
}), 400
try:
payload = JWTService.decode_token(refresh_token, expected_type='refresh')
user_id = int(payload.get('sub'))
user = user_service.get_by_id(user_id)
if not user or not user.is_active:
return jsonify({
'error': 'Unauthorized',
'message': 'Usuario no encontrado o inactivo.'
}), 401
new_access_token = JWTService.create_access_token(user)
return jsonify({
'access_token': new_access_token,
'token_type': 'Bearer',
'expires_in': int(JWTService.ACCESS_TOKEN_EXPIRES.total_seconds())
}), 200
except jwt.ExpiredSignatureError:
return jsonify({'error': 'TokenExpired', 'message': 'El refresh token ha expirado. Reingrese credenciales.'}), 401
except jwt.InvalidTokenError as e:
return jsonify({'error': 'InvalidToken', 'message': str(e)}), 401
@api_auth_bp.route('/logout', methods=['POST'])
@jwt_required
def logout():
"""
Cierre de sesión: revoca el token de acceso activo y limpia cookies.
"""
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')
return resp
@api_auth_bp.route('/me', methods=['GET'])
@jwt_required
def get_current_user():
"""
Retorna el perfil y los permisos del usuario autenticado vía JWT.
"""
profile = user_service.get_profile_data(g.jwt_user)
return jsonify(profile), 200
+119
View File
@@ -0,0 +1,119 @@
from flask import Blueprint, request, jsonify, g
from pydantic import ValidationError
from app.services.classroom_service import ClassroomService
from app.schemas.classroom_dto import ClassroomCreateDTO, ClassroomUpdateDTO, ClassroomResponseDTO
from app.utils.jwt_decorators import jwt_required, jwt_role_required
api_classrooms_bp = Blueprint('api_classrooms', __name__, url_prefix='/api/v1/classrooms')
classroom_service = ClassroomService()
@api_classrooms_bp.route('', methods=['GET'])
@jwt_required
def list_classrooms():
"""Lista aulas con filtros opcionales (building_id, floor, mode)."""
building_id = request.args.get('building_id', type=int)
floor = request.args.get('floor')
mode = request.args.get('mode', '').lower()
only_virtual = mode == 'virtual'
only_physical = mode == 'physical'
classrooms = classroom_service.list_classrooms(
building_id=building_id,
floor=floor,
only_virtual=only_virtual,
only_physical=only_physical
)
result = []
for c in classrooms:
result.append({
'id': c.id,
'code': c.code,
'building': c.building_name,
'building_id': c.building_id,
'floor': c.floor,
'floor_display': c.floor_display,
'capacity': c.capacity,
'is_virtual': c.is_virtual,
'location_display': c.location_display,
'description': c.description,
'is_active': c.is_active
})
return jsonify({'total': len(result), 'classrooms': result}), 200
@api_classrooms_bp.route('/<int:classroom_id>', methods=['GET'])
@jwt_required
def get_classroom(classroom_id: int):
"""Obtiene el detalle de un aula por ID."""
c = classroom_service.get_classroom(classroom_id)
if not c:
return jsonify({'error': 'NotFound', 'message': f'Aula {classroom_id} no encontrada.'}), 404
return jsonify({
'id': c.id,
'code': c.code,
'building': c.building_name,
'building_id': c.building_id,
'floor': c.floor,
'floor_display': c.floor_display,
'capacity': c.capacity,
'is_virtual': c.is_virtual,
'location_display': c.location_display,
'description': c.description,
'is_active': c.is_active
}), 200
@api_classrooms_bp.route('', methods=['POST'])
@jwt_role_required('ADMIN', 'ADMINISTRADOR', 'BEDELIA')
def create_classroom():
"""Crea una nueva aula validando el contrato con ClassroomCreateDTO."""
data = request.get_json(silent=True) or {}
try:
dto = ClassroomCreateDTO(**data)
except ValidationError as e:
return jsonify({'error': 'ValidationError', 'details': e.errors()}), 400
try:
classroom = classroom_service.create_classroom(dto)
return jsonify({
'message': 'Aula creada exitosamente.',
'id': classroom.id,
'code': classroom.code,
'location_display': classroom.location_display
}), 201
except ValueError as e:
return jsonify({'error': 'ConflictOrValidation', 'message': str(e)}), 400
@api_classrooms_bp.route('/<int:classroom_id>', methods=['PUT'])
@jwt_role_required('ADMIN', 'ADMINISTRADOR', 'BEDELIA')
def update_classroom(classroom_id: int):
"""Actualiza los datos de un aula."""
data = request.get_json(silent=True) or {}
try:
dto = ClassroomUpdateDTO(**data)
except ValidationError as e:
return jsonify({'error': 'ValidationError', 'details': e.errors()}), 400
try:
classroom = classroom_service.update_classroom(classroom_id, dto)
return jsonify({
'message': 'Aula actualizada exitosamente.',
'id': classroom.id,
'code': classroom.code,
'capacity': classroom.capacity
}), 200
except ValueError as e:
return jsonify({'error': 'ConflictOrValidation', 'message': str(e)}), 400
@api_classrooms_bp.route('/<int:classroom_id>', methods=['DELETE'])
@jwt_role_required('ADMIN', 'ADMINISTRADOR')
def delete_classroom(classroom_id: int):
"""Elimina o desactiva un aula."""
deleted = classroom_service.delete_classroom(classroom_id)
if not deleted:
return jsonify({'error': 'NotFound', 'message': f'Aula {classroom_id} no encontrada.'}), 404
return jsonify({'message': f'Aula {classroom_id} eliminada/desactivada correctamente.'}), 200
+140
View File
@@ -0,0 +1,140 @@
from flask import Blueprint, request, jsonify, g
from datetime import datetime, timedelta, date
from pydantic import ValidationError
from app.services.reservation_service import ReservationService
from app.schemas.reservation_dto import ReservationCreateDTO, ReservationUpdateDTO
from app.utils.jwt_decorators import jwt_required, jwt_role_required
api_reservations_bp = Blueprint('api_reservations', __name__, url_prefix='/api/v1/reservations')
reservation_service = ReservationService()
@api_reservations_bp.route('', methods=['GET'])
@jwt_required
def list_reservations():
"""Consulta de reservas por rango de fechas y/o aula."""
start_str = request.args.get('start_date')
end_str = request.args.get('end_date')
classroom_id = request.args.get('classroom_id', type=int)
now = datetime.utcnow()
try:
start_dt = datetime.strptime(start_str, '%Y-%m-%d') if start_str else now.replace(hour=0, minute=0, second=0)
except ValueError:
return jsonify({'error': 'BadRequest', 'message': 'Formato inválido de start_date (debe ser YYYY-MM-DD).'}), 400
try:
end_dt = datetime.strptime(end_str, '%Y-%m-%d').replace(hour=23, minute=59, second=59) if end_str else start_dt + timedelta(days=7)
except ValueError:
return jsonify({'error': 'BadRequest', 'message': 'Formato inválido de end_date (debe ser YYYY-MM-DD).'}), 400
reservations = reservation_service.list_reservations(start_dt, end_dt, classroom_id=classroom_id)
result = []
for r in reservations:
result.append({
'id': r.id,
'classroom_id': r.classroom_id,
'classroom_name': r.classroom.code if r.classroom else None,
'commission_id': r.commission_id,
'teacher_name': r.user.name if r.user else None,
'start_time': r.start_time.isoformat(),
'end_time': r.end_time.isoformat(),
'purpose': r.purpose,
'status': str(r.status),
'shift': r.shift,
'virtual_link': r.virtual_link,
'expected_attendees': r.expected_attendees
})
return jsonify({
'total': len(result),
'start_date': start_dt.strftime('%Y-%m-%d'),
'end_date': end_dt.strftime('%Y-%m-%d'),
'reservations': result
}), 200
@api_reservations_bp.route('/<int:reservation_id>', methods=['GET'])
@jwt_required
def get_reservation(reservation_id: int):
"""Obtiene el detalle de una reserva específica."""
r = reservation_service.get_reservation(reservation_id)
if not r:
return jsonify({'error': 'NotFound', 'message': f'Reserva {reservation_id} no encontrada.'}), 404
return jsonify({
'id': r.id,
'classroom_id': r.classroom_id,
'classroom_name': r.classroom.code if r.classroom else None,
'location_display': r.classroom.location_display if r.classroom else None,
'commission_id': r.commission_id,
'teacher_id': r.user_id,
'teacher_name': r.user.name if r.user else None,
'start_time': r.start_time.isoformat(),
'end_time': r.end_time.isoformat(),
'purpose': r.purpose,
'status': str(r.status),
'shift': r.shift,
'virtual_link': r.virtual_link,
'expected_attendees': r.expected_attendees,
'notes': r.notes
}), 200
@api_reservations_bp.route('', methods=['POST'])
@jwt_required
def create_reservation():
"""Crea una reserva aplicando validación DTO y detección de colisiones."""
data = request.get_json(silent=True) or {}
# Inyectar usuario autenticado si no se especifica
if 'user_id' not in data:
data['user_id'] = g.jwt_user.id
try:
dto = ReservationCreateDTO(**data)
except ValidationError as e:
return jsonify({'error': 'ValidationError', 'details': e.errors()}), 400
try:
reservation = reservation_service.create_reservation(dto)
return jsonify({
'message': 'Reserva creada exitosamente.',
'id': reservation.id,
'classroom_id': reservation.classroom_id,
'start_time': reservation.start_time.isoformat(),
'end_time': reservation.end_time.isoformat(),
'status': str(reservation.status)
}), 201
except ValueError as e:
return jsonify({'error': 'ConflictOrValidation', 'message': str(e)}), 409
@api_reservations_bp.route('/<int:reservation_id>', methods=['PUT'])
@jwt_required
def update_reservation(reservation_id: int):
"""Modifica una reserva existente."""
data = request.get_json(silent=True) or {}
try:
dto = ReservationUpdateDTO(**data)
except ValidationError as e:
return jsonify({'error': 'ValidationError', 'details': e.errors()}), 400
try:
reservation = reservation_service.update_reservation(reservation_id, dto)
return jsonify({
'message': 'Reserva actualizada exitosamente.',
'id': reservation.id,
'start_time': reservation.start_time.isoformat(),
'end_time': reservation.end_time.isoformat(),
'status': str(reservation.status)
}), 200
except ValueError as e:
return jsonify({'error': 'ConflictOrValidation', 'message': str(e)}), 409
@api_reservations_bp.route('/<int:reservation_id>', methods=['DELETE'])
@jwt_required
def cancel_reservation(reservation_id: int):
"""Cancela una reserva."""
cancelled = reservation_service.cancel_reservation(reservation_id)
if not cancelled:
return jsonify({'error': 'NotFound', 'message': f'Reserva {reservation_id} no encontrada.'}), 404
return jsonify({'message': f'Reserva {reservation_id} cancelada correctamente.'}), 200
+14 -6
View File
@@ -58,29 +58,37 @@ def add_classroom():
cap_raw = str(form.capacity.data or '').strip()
if cap_raw in ['∞', 'inf', 'INF', 'Infinity', 'infinity', '0', 'ilimitada', 'Ilimitada', 'sin limite', 'Sin límite']:
cap_val = 0
cap_val = 9999
else:
cap_val = int(cap_raw)
classroom = Classroom(
from app.services.classroom_service import ClassroomService
from app.schemas.classroom_dto import ClassroomCreateDTO
from app.services.audit_service import AuditService
dto = ClassroomCreateDTO(
building_id=building.id,
building=building.name,
code=room_code,
floor=floor_val,
capacity=cap_val,
description=form.description.data,
is_active=form.is_active.data
)
classroom_service = ClassroomService()
classroom = classroom_service.create_classroom(dto)
db.session.add(classroom)
db.session.commit()
# Registrar en bitácora inmutable de auditoría
AuditService.log('CREATE', 'classrooms', entity_id=classroom.id, details={'code': classroom.code, 'building': building.name})
flash(f'Aula {classroom.location_display} creada exitosamente.', 'success')
return redirect(url_for('classrooms.list_classrooms'))
except ValueError as ve:
flash(str(ve), 'error')
return render_template('classrooms/add.html', form=form, building_floors=building_floors, title='Add Classroom')
except Exception as e:
db.session.rollback()
flash(f'Error creating classroom: {str(e)}', 'error')
flash(f'Error al crear el aula: {str(e)}', 'error')
return render_template('classrooms/add.html', form=form, building_floors=building_floors, title='Add Classroom')