feat(reception): add strict anti-capture expiration to dynamic QR and fix Buenos Aires timezone display (v3.8.49)
This commit is contained in:
@@ -7,7 +7,7 @@ from typing import Any
|
||||
from database import db, get_db, engine, SessionLocal, session
|
||||
from config.config import Config
|
||||
|
||||
__version__ = "3.8.48"
|
||||
__version__ = "3.8.49"
|
||||
|
||||
class DummyContext:
|
||||
def __enter__(self):
|
||||
|
||||
@@ -82,6 +82,33 @@ class QRSecurityService:
|
||||
if clean_normalized.startswith("UNICABA:QR:"):
|
||||
clean_normalized = clean_normalized[len("UNICABA:QR:"):].strip()
|
||||
|
||||
# 1. Intentar validar como JWT criptográfico institucional primero
|
||||
if clean_normalized.count(".") == 2:
|
||||
try:
|
||||
payload = jwt.decode(
|
||||
clean_normalized,
|
||||
cls._get_secret(),
|
||||
algorithms=["HS256"],
|
||||
options={"verify_exp": True}
|
||||
)
|
||||
if payload.get("type") != cls.QR_TOKEN_TYPE:
|
||||
return None, "DENEGADO", "El token no corresponde a una credencial institucional válida."
|
||||
|
||||
user_id = payload.get("sub")
|
||||
user = User.query.get(int(user_id)) if user_id else None
|
||||
if not user:
|
||||
return None, "DENEGADO", "Usuario no encontrado en la base de datos."
|
||||
|
||||
if not user.is_active:
|
||||
return user, "RESTRINGIDO", "La cuenta del usuario se encuentra inactiva o suspendida."
|
||||
|
||||
return user, "AUTORIZADO", "Credencial institucional válida y activa."
|
||||
except jwt.ExpiredSignatureError:
|
||||
return None, "DENEGADO", "La credencial digital ha expirado (anti-captura activo). Renueve el código en la pantalla del usuario."
|
||||
except jwt.PyJWTError as e:
|
||||
return None, "DENEGADO", f"Firma criptográfica inválida: {str(e)}"
|
||||
|
||||
# 2. Formatos fallback (cuando no es un JWT):
|
||||
# A. Intentar extraer patrón institucional UNICABA:USR:<id>
|
||||
usr_match = re.search(r"USR:(\d+)", clean_normalized)
|
||||
if usr_match:
|
||||
@@ -107,32 +134,6 @@ class QRSecurityService:
|
||||
return user_by_dni, "RESTRINGIDO", "Usuario inactivo en el sistema institucional."
|
||||
return user_by_dni, "AUTORIZADO", f"Identificación validada por documento de identidad (DNI {doc})."
|
||||
|
||||
# C. Intentar validar como JWT institucional
|
||||
if clean_normalized.count(".") == 2:
|
||||
try:
|
||||
payload = jwt.decode(
|
||||
clean_normalized,
|
||||
cls._get_secret(),
|
||||
algorithms=["HS256"],
|
||||
options={"verify_exp": True}
|
||||
)
|
||||
if payload.get("type") != cls.QR_TOKEN_TYPE:
|
||||
return None, "DENEGADO", "El token no corresponde a una credencial institucional válida."
|
||||
|
||||
user_id = payload.get("sub")
|
||||
user = User.query.get(int(user_id)) if user_id else None
|
||||
if not user:
|
||||
return None, "DENEGADO", "Usuario no encontrado en la base de datos."
|
||||
|
||||
if not user.is_active:
|
||||
return user, "RESTRINGIDO", "La cuenta del usuario se encuentra inactiva o suspendida."
|
||||
|
||||
return user, "AUTORIZADO", "Credencial institucional válida y activa."
|
||||
except jwt.ExpiredSignatureError:
|
||||
return None, "DENEGADO", "La credencial digital ha expirado. El alumno debe abrir su app para renovarla."
|
||||
except jwt.PyJWTError as e:
|
||||
return None, "DENEGADO", f"Firma criptográfica inválida: {str(e)}"
|
||||
|
||||
# D. Fallback: Lectura de pistola óptica o documento directo (ej: 'DNI:12345678' o '12345678')
|
||||
doc_num = clean_normalized
|
||||
if doc_num.upper().startswith("DNI:"):
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional, List
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from typing import Optional, List, Tuple
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||
|
||||
from app import db
|
||||
@@ -20,6 +20,25 @@ from schemas.reception_dto import (
|
||||
router = APIRouter(prefix="/api/v1/reception", tags=["Reception & Access Control"])
|
||||
|
||||
|
||||
def to_argentina_time(dt_val: Optional[datetime]) -> Tuple[str, str]:
|
||||
"""Convierte un datetime (UTC) a la hora local institucional de Buenos Aires (UTC-3)."""
|
||||
if not dt_val:
|
||||
return "", "--"
|
||||
try:
|
||||
from zoneinfo import ZoneInfo
|
||||
tz_ar = ZoneInfo("America/Argentina/Buenos_Aires")
|
||||
if dt_val.tzinfo is None:
|
||||
dt_utc = dt_val.replace(tzinfo=timezone.utc)
|
||||
else:
|
||||
dt_utc = dt_val.astimezone(timezone.utc)
|
||||
local_dt = dt_utc.astimezone(tz_ar)
|
||||
except Exception:
|
||||
offset = timedelta(hours=-3)
|
||||
local_dt = (dt_val if dt_val.tzinfo is None else dt_val.replace(tzinfo=None)) + offset
|
||||
|
||||
return local_dt.isoformat(), local_dt.strftime("%H:%M hs")
|
||||
|
||||
|
||||
@router.post("/verify-qr", response_model=QRVerificationResponseDTO)
|
||||
def verify_qr_and_register_access(
|
||||
payload: QRVerificationRequestDTO,
|
||||
@@ -68,6 +87,8 @@ def verify_qr_and_register_access(
|
||||
else f"Acceso observado: {reason}"
|
||||
)
|
||||
|
||||
scanned_at_iso, scanned_time_str = to_argentina_time(now_utc)
|
||||
|
||||
return QRVerificationResponseDTO(
|
||||
status=auth_status,
|
||||
message=message,
|
||||
@@ -78,7 +99,8 @@ def verify_qr_and_register_access(
|
||||
matricula_status="REGULAR / ACTIVO" if user.is_active else "SUSPENDIDO / INACTIVO",
|
||||
photo_url=None,
|
||||
todays_classes=classes,
|
||||
scanned_at=now_utc.isoformat()
|
||||
scanned_at=scanned_at_iso,
|
||||
scanned_time=scanned_time_str
|
||||
)
|
||||
|
||||
# Si el código QR es inválido o el usuario no existe
|
||||
@@ -90,6 +112,8 @@ def verify_qr_and_register_access(
|
||||
details={"reason": reason, "raw_snippet": payload.qr_token[:15]}
|
||||
)
|
||||
|
||||
scanned_at_iso, scanned_time_str = to_argentina_time(now_utc)
|
||||
|
||||
return QRVerificationResponseDTO(
|
||||
status="DENEGADO",
|
||||
message=reason,
|
||||
@@ -100,7 +124,8 @@ def verify_qr_and_register_access(
|
||||
matricula_status="NO REGISTRADO",
|
||||
photo_url=None,
|
||||
todays_classes=[],
|
||||
scanned_at=now_utc.isoformat()
|
||||
scanned_at=scanned_at_iso,
|
||||
scanned_time=scanned_time_str
|
||||
)
|
||||
|
||||
|
||||
@@ -112,7 +137,7 @@ def get_recent_access_logs(
|
||||
):
|
||||
"""
|
||||
Retorna los últimos ingresos registrados en el punto de acceso.
|
||||
Permite monitoreo en tiempo real para el personal de Recepción y Seguridad.
|
||||
Permite monitoreo en tiempo real para el personal de Recepción y Seguridad con hora local de Buenos Aires.
|
||||
"""
|
||||
query = AccessLogQR.query
|
||||
if building_id:
|
||||
@@ -122,6 +147,7 @@ def get_recent_access_logs(
|
||||
|
||||
items = []
|
||||
for l in logs:
|
||||
scanned_at_iso, scanned_time_str = to_argentina_time(l.scanned_at)
|
||||
items.append(AccessLogResponseDTO(
|
||||
id=l.id,
|
||||
user_name=l.user.name if l.user else "Usuario no disponible",
|
||||
@@ -129,7 +155,8 @@ def get_recent_access_logs(
|
||||
user_role=l.user.role if l.user else None,
|
||||
building_name=l.building.name if l.building else "Sede no especificada",
|
||||
scanned_by_name=l.scanned_by.name if l.scanned_by else "Recepción",
|
||||
scanned_at=l.scanned_at.isoformat(),
|
||||
scanned_at=scanned_at_iso,
|
||||
scanned_time=scanned_time_str,
|
||||
status=l.status,
|
||||
reason=l.reason
|
||||
))
|
||||
@@ -147,10 +174,16 @@ def get_my_credential_qr_token(
|
||||
"""
|
||||
Genera y entrega el token criptográfico del código QR para la credencial digital
|
||||
del usuario autenticado (estudiante o docente).
|
||||
Soporta rotación dinámica periódica (default 3s) configurada en SystemSetting.
|
||||
Soporta rotación dinámica periódica (default 3s) y ventana de validez anti-captura estricta (default 6s).
|
||||
"""
|
||||
renewal_seconds = int(SystemSetting.get_value('qr_renewal_interval_seconds', 3) or 3)
|
||||
grace_seconds = int(SystemSetting.get_value('qr_token_grace_period_seconds', 60) or 60)
|
||||
# Ventana estricta anti-captura: el token expira pasados pocos segundos (default 6s)
|
||||
# de modo que una captura de pantalla de 10 segundos queda garantizadamente rechazada.
|
||||
configured_grace = SystemSetting.get_value('qr_token_grace_period_seconds', None)
|
||||
if configured_grace is not None:
|
||||
grace_seconds = int(configured_grace)
|
||||
else:
|
||||
grace_seconds = max(renewal_seconds + 3, 6)
|
||||
|
||||
token = QRSecurityService.generate_qr_token(current_user, valid_seconds=grace_seconds)
|
||||
return {
|
||||
|
||||
@@ -31,6 +31,7 @@ class QRVerificationResponseDTO(BaseModel):
|
||||
photo_url: Optional[str] = None
|
||||
todays_classes: List[TodayClassDTO] = Field(default_factory=list, description="Clases presenciales o virtuales asignadas para hoy")
|
||||
scanned_at: str = Field(..., description="Timestamp de registro del escaneo")
|
||||
scanned_time: Optional[str] = Field(None, description="Hora formateada en zona horaria local de Buenos Aires (HH:MM hs)")
|
||||
|
||||
|
||||
class AccessLogResponseDTO(BaseModel):
|
||||
@@ -41,6 +42,7 @@ class AccessLogResponseDTO(BaseModel):
|
||||
building_name: str
|
||||
scanned_by_name: str
|
||||
scanned_at: str
|
||||
scanned_time: Optional[str] = None
|
||||
status: str
|
||||
reason: Optional[str] = None
|
||||
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@ from setuptools import setup, find_packages
|
||||
|
||||
setup(
|
||||
name="edu-space-admin",
|
||||
version="3.8.48",
|
||||
version="3.8.49",
|
||||
description="Administrative interface for Edu-Space Classroom Management System (FastAPI ASGI Core)",
|
||||
author="Edu-Space Development Team",
|
||||
author_email="admin@edu-space.com",
|
||||
|
||||
@@ -246,8 +246,15 @@ def test_reception_my_qr_token_endpoint(init_database):
|
||||
assert data["user_name"] == "Valeria Paz"
|
||||
assert "renewal_interval_seconds" in data
|
||||
assert data["renewal_interval_seconds"] == 3
|
||||
assert "grace_period_seconds" in data
|
||||
assert data["grace_period_seconds"] == 60
|
||||
assert data["grace_period_seconds"] == 6
|
||||
|
||||
# Verificar que el token expire y sea rechazado ante capturas de pantalla viejas (> 6s)
|
||||
expired_token = QRSecurityService.generate_qr_token(student, valid_seconds=1)
|
||||
import time
|
||||
time.sleep(1.1)
|
||||
exp_user, exp_status, exp_reason = QRSecurityService.decode_and_resolve_user(expired_token)
|
||||
assert exp_status == "DENEGADO"
|
||||
assert "expirado" in exp_reason.lower()
|
||||
|
||||
|
||||
def test_security_qr_settings_configuration(init_database):
|
||||
|
||||
Reference in New Issue
Block a user