fix(types): sanitizar extraccion de payload y tipado estricto en buildings y reservations

This commit is contained in:
2026-10-19 15:02:47 -03:00
parent ae329c4c36
commit 263e0a17a6
3 changed files with 58 additions and 49 deletions
+15
View File
@@ -118,3 +118,18 @@ def require_roles(allowed_roles: List[str]) -> Callable:
)
return role_dependency
async def get_request_payload(request: Request) -> dict[str, Any]:
"""Extrae el cuerpo JSON o formulario multiparte sanitizado como diccionario de Python."""
try:
body = await request.json()
if isinstance(body, dict):
return body
except Exception:
pass
try:
form = await request.form()
return {str(k): str(v) for k, v in form.items()}
except Exception:
return {}
+21 -23
View File
@@ -11,7 +11,7 @@ from app import db
from app.models.building import Building
from app.models.classroom import Classroom
from app.services.audit_service import AuditService
from dependencies import get_current_user, require_roles
from dependencies import get_current_user, require_roles, get_request_payload
from app.models.user import User
from database import get_flask_app
@@ -96,22 +96,21 @@ async def create_building(
current_user: User = Depends(require_roles(["ADMIN", "BEDELIA"]))
):
"""Crea una nueva sede o edificio institucional."""
data = {}
try:
data = await request.json()
except Exception:
form = await request.form()
data = dict(form)
data = await get_request_payload(request)
with flask_app.app_context():
name = (data.get('name') or '').strip()
code = (data.get('code') or '').strip().upper() or None
address = (data.get('address') or '').strip() or None
name = str(data.get('name') or '').strip()
code_str = str(data.get('code') or '').strip().upper()
code = code_str if code_str else None
address_str = str(data.get('address') or '').strip()
address = address_str if address_str else None
try:
floors = int(data.get('floors', 1) or 1)
floors_val = data.get('floors', 1)
floors = int(str(floors_val)) if floors_val is not None else 1
except (ValueError, TypeError):
floors = 1
description = (data.get('description') or '').strip() or None
desc_str = str(data.get('description') or '').strip()
description = desc_str if desc_str else None
is_active = data.get('is_active', True)
if isinstance(is_active, str):
is_active = is_active.lower() in ['true', '1', 'on']
@@ -157,19 +156,14 @@ async def update_building(
current_user: User = Depends(require_roles(["ADMIN", "BEDELIA"]))
):
"""Actualiza la información de un edificio existente."""
data = {}
try:
data = await request.json()
except Exception:
form = await request.form()
data = dict(form)
data = await get_request_payload(request)
with flask_app.app_context():
building = Building.query.get(id)
if not building:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Edificio con ID {id} no encontrado.")
name = (data.get('name') or '').strip()
name = str(data.get('name') or '').strip()
if not name:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="El nombre del edificio es obligatorio.")
@@ -183,16 +177,20 @@ async def update_building(
old_name = building.name
building.name = name
if 'code' in data:
building.code = (data.get('code') or '').strip().upper() or None
c_val = str(data.get('code') or '').strip().upper()
building.code = c_val if c_val else None
if 'address' in data:
building.address = (data.get('address') or '').strip() or None
a_val = str(data.get('address') or '').strip()
building.address = a_val if a_val else None
if 'floors' in data:
try:
building.floors = int(data.get('floors', 0) or 0)
fl_val = data.get('floors', 0)
building.floors = int(str(fl_val)) if fl_val is not None else 0
except (ValueError, TypeError):
pass
if 'description' in data:
building.description = (data.get('description') or '').strip() or None
d_val = str(data.get('description') or '').strip()
building.description = d_val if d_val else None
if 'is_active' in data:
is_active = data.get('is_active')
if isinstance(is_active, str):
+22 -26
View File
@@ -13,7 +13,7 @@ from app.models.subject import Commission
from app.services.reservation_service import ReservationService
from app.services.audit_service import AuditService
from app.schemas.reservation_dto import ReservationCreateDTO, ReservationUpdateDTO
from dependencies import get_current_user
from dependencies import get_current_user, get_request_payload
from app.models.user import User
from database import get_flask_app
@@ -398,35 +398,31 @@ async def drag_update_reservation(
current_user: User = Depends(get_current_user)
):
"""Actualización o creación rápida de reserva mediante arrastre en la grilla semanal."""
data = {}
try:
data = await request.json()
except Exception:
form = await request.form()
data = dict(form)
data = await get_request_payload(request)
reservation_id = data.get('reservation_id')
commission_id = data.get('commission_id')
classroom_id = data.get('classroom_id')
start_time_str = data.get('start_time')
end_time_str = data.get('end_time')
if not classroom_id or not start_time_str or not end_time_str:
res_id_raw = data.get('reservation_id')
reservation_id = int(str(res_id_raw)) if res_id_raw is not None and str(res_id_raw).isdigit() else None
comm_id_raw = data.get('commission_id')
commission_id = int(str(comm_id_raw)) if comm_id_raw is not None and str(comm_id_raw).isdigit() else None
cls_id_raw = data.get('classroom_id')
if cls_id_raw is None or not str(cls_id_raw).isdigit():
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Faltan parámetros obligatorios (aula, inicio, fin)."
detail="classroom_id es obligatorio y debe ser numérico."
)
classroom_id = int(str(cls_id_raw))
start_time_str = str(data.get('start_time') or '').strip()
end_time_str = str(data.get('end_time') or '').strip()
if not start_time_str or not end_time_str:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Faltan parámetros obligatorios (inicio, fin)."
)
try:
if isinstance(start_time_str, str):
start_dt = datetime.fromisoformat(start_time_str.replace('Z', '+00:00'))
else:
start_dt = start_time_str
if isinstance(end_time_str, str):
end_dt = datetime.fromisoformat(end_time_str.replace('Z', '+00:00'))
else:
end_dt = end_time_str
start_dt: datetime = datetime.fromisoformat(start_time_str.replace('Z', '+00:00'))
end_dt: datetime = datetime.fromisoformat(end_time_str.replace('Z', '+00:00'))
except Exception as e:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
@@ -438,8 +434,8 @@ async def drag_update_reservation(
if not classroom:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Aula no encontrada.")
effective_comm_id = commission_id
if not effective_comm_id and reservation_id:
effective_comm_id: Optional[int] = commission_id
if effective_comm_id is None and reservation_id:
existing_res = db.session.get(Reservation, reservation_id)
if existing_res:
effective_comm_id = existing_res.commission_id