fix(types): sanitizar extraccion de payload y tipado estricto en buildings y reservations
This commit is contained in:
@@ -118,3 +118,18 @@ def require_roles(allowed_roles: List[str]) -> Callable:
|
|||||||
)
|
)
|
||||||
|
|
||||||
return role_dependency
|
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 {}
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ from app import db
|
|||||||
from app.models.building import Building
|
from app.models.building import Building
|
||||||
from app.models.classroom import Classroom
|
from app.models.classroom import Classroom
|
||||||
from app.services.audit_service import AuditService
|
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 app.models.user import User
|
||||||
from database import get_flask_app
|
from database import get_flask_app
|
||||||
|
|
||||||
@@ -96,22 +96,21 @@ async def create_building(
|
|||||||
current_user: User = Depends(require_roles(["ADMIN", "BEDELIA"]))
|
current_user: User = Depends(require_roles(["ADMIN", "BEDELIA"]))
|
||||||
):
|
):
|
||||||
"""Crea una nueva sede o edificio institucional."""
|
"""Crea una nueva sede o edificio institucional."""
|
||||||
data = {}
|
data = await get_request_payload(request)
|
||||||
try:
|
|
||||||
data = await request.json()
|
|
||||||
except Exception:
|
|
||||||
form = await request.form()
|
|
||||||
data = dict(form)
|
|
||||||
|
|
||||||
with flask_app.app_context():
|
with flask_app.app_context():
|
||||||
name = (data.get('name') or '').strip()
|
name = str(data.get('name') or '').strip()
|
||||||
code = (data.get('code') or '').strip().upper() or None
|
code_str = str(data.get('code') or '').strip().upper()
|
||||||
address = (data.get('address') or '').strip() or None
|
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:
|
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):
|
except (ValueError, TypeError):
|
||||||
floors = 1
|
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)
|
is_active = data.get('is_active', True)
|
||||||
if isinstance(is_active, str):
|
if isinstance(is_active, str):
|
||||||
is_active = is_active.lower() in ['true', '1', 'on']
|
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"]))
|
current_user: User = Depends(require_roles(["ADMIN", "BEDELIA"]))
|
||||||
):
|
):
|
||||||
"""Actualiza la información de un edificio existente."""
|
"""Actualiza la información de un edificio existente."""
|
||||||
data = {}
|
data = await get_request_payload(request)
|
||||||
try:
|
|
||||||
data = await request.json()
|
|
||||||
except Exception:
|
|
||||||
form = await request.form()
|
|
||||||
data = dict(form)
|
|
||||||
|
|
||||||
with flask_app.app_context():
|
with flask_app.app_context():
|
||||||
building = Building.query.get(id)
|
building = Building.query.get(id)
|
||||||
if not building:
|
if not building:
|
||||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Edificio con ID {id} no encontrado.")
|
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:
|
if not name:
|
||||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="El nombre del edificio es obligatorio.")
|
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
|
old_name = building.name
|
||||||
building.name = name
|
building.name = name
|
||||||
if 'code' in data:
|
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:
|
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:
|
if 'floors' in data:
|
||||||
try:
|
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):
|
except (ValueError, TypeError):
|
||||||
pass
|
pass
|
||||||
if 'description' in data:
|
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:
|
if 'is_active' in data:
|
||||||
is_active = data.get('is_active')
|
is_active = data.get('is_active')
|
||||||
if isinstance(is_active, str):
|
if isinstance(is_active, str):
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ from app.models.subject import Commission
|
|||||||
from app.services.reservation_service import ReservationService
|
from app.services.reservation_service import ReservationService
|
||||||
from app.services.audit_service import AuditService
|
from app.services.audit_service import AuditService
|
||||||
from app.schemas.reservation_dto import ReservationCreateDTO, ReservationUpdateDTO
|
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 app.models.user import User
|
||||||
from database import get_flask_app
|
from database import get_flask_app
|
||||||
|
|
||||||
@@ -398,35 +398,31 @@ async def drag_update_reservation(
|
|||||||
current_user: User = Depends(get_current_user)
|
current_user: User = Depends(get_current_user)
|
||||||
):
|
):
|
||||||
"""Actualización o creación rápida de reserva mediante arrastre en la grilla semanal."""
|
"""Actualización o creación rápida de reserva mediante arrastre en la grilla semanal."""
|
||||||
data = {}
|
data = await get_request_payload(request)
|
||||||
try:
|
|
||||||
data = await request.json()
|
|
||||||
except Exception:
|
|
||||||
form = await request.form()
|
|
||||||
data = dict(form)
|
|
||||||
|
|
||||||
reservation_id = data.get('reservation_id')
|
res_id_raw = data.get('reservation_id')
|
||||||
commission_id = data.get('commission_id')
|
reservation_id = int(str(res_id_raw)) if res_id_raw is not None and str(res_id_raw).isdigit() else None
|
||||||
classroom_id = data.get('classroom_id')
|
comm_id_raw = data.get('commission_id')
|
||||||
start_time_str = data.get('start_time')
|
commission_id = int(str(comm_id_raw)) if comm_id_raw is not None and str(comm_id_raw).isdigit() else None
|
||||||
end_time_str = data.get('end_time')
|
cls_id_raw = data.get('classroom_id')
|
||||||
|
if cls_id_raw is None or not str(cls_id_raw).isdigit():
|
||||||
if not classroom_id or not start_time_str or not end_time_str:
|
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=status.HTTP_400_BAD_REQUEST,
|
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:
|
try:
|
||||||
if isinstance(start_time_str, str):
|
start_dt: datetime = datetime.fromisoformat(start_time_str.replace('Z', '+00:00'))
|
||||||
start_dt = datetime.fromisoformat(start_time_str.replace('Z', '+00:00'))
|
end_dt: datetime = datetime.fromisoformat(end_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
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=status.HTTP_400_BAD_REQUEST,
|
status_code=status.HTTP_400_BAD_REQUEST,
|
||||||
@@ -438,8 +434,8 @@ async def drag_update_reservation(
|
|||||||
if not classroom:
|
if not classroom:
|
||||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Aula no encontrada.")
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Aula no encontrada.")
|
||||||
|
|
||||||
effective_comm_id = commission_id
|
effective_comm_id: Optional[int] = commission_id
|
||||||
if not effective_comm_id and reservation_id:
|
if effective_comm_id is None and reservation_id:
|
||||||
existing_res = db.session.get(Reservation, reservation_id)
|
existing_res = db.session.get(Reservation, reservation_id)
|
||||||
if existing_res:
|
if existing_res:
|
||||||
effective_comm_id = existing_res.commission_id
|
effective_comm_id = existing_res.commission_id
|
||||||
|
|||||||
Reference in New Issue
Block a user