feat(qr): add 3-second dynamic QR auto-rotation and global settings configuration (v3.8.46)
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.45"
|
||||
__version__ = "3.8.46"
|
||||
|
||||
class DummyContext:
|
||||
def __enter__(self):
|
||||
|
||||
@@ -32,12 +32,19 @@ class QRSecurityService:
|
||||
return getattr(Config, 'SECRET_KEY', 'unicaba-secret-qr-key')
|
||||
|
||||
@classmethod
|
||||
def generate_qr_token(cls, user: User, hours_valid: int = DEFAULT_VALID_HOURS) -> str:
|
||||
def generate_qr_token(
|
||||
cls,
|
||||
user: User,
|
||||
hours_valid: int = DEFAULT_VALID_HOURS,
|
||||
valid_seconds: Optional[int] = None
|
||||
) -> str:
|
||||
"""
|
||||
Emite un token JWT firmado de credencial institucional para el usuario.
|
||||
Contiene identificación, rol, DNI y tiempo de expiración.
|
||||
Soporta valid_seconds para tokens dinámicos rotativos anti-captura.
|
||||
"""
|
||||
now = datetime.now(timezone.utc)
|
||||
exp_delta = timedelta(seconds=valid_seconds) if valid_seconds is not None else timedelta(hours=hours_valid)
|
||||
payload = {
|
||||
"sub": str(user.id),
|
||||
"dni": user.document_number or "",
|
||||
@@ -46,7 +53,7 @@ class QRSecurityService:
|
||||
"type": cls.QR_TOKEN_TYPE,
|
||||
"jti": str(uuid.uuid4())[:8],
|
||||
"iat": now,
|
||||
"exp": now + timedelta(hours=hours_valid)
|
||||
"exp": now + exp_delta
|
||||
}
|
||||
return jwt.encode(payload, cls._get_secret(), algorithm="HS256")
|
||||
|
||||
|
||||
@@ -874,6 +874,11 @@ def get_all_settings(current_user: User = Depends(require_roles(["ADMIN"]))):
|
||||
'output_limit': int(SystemSetting.get_value('ai_chat_output_limit', 65536) or 65536)
|
||||
}
|
||||
|
||||
security_qr = {
|
||||
'renewal_interval_seconds': int(SystemSetting.get_value('qr_renewal_interval_seconds', 3) or 3),
|
||||
'grace_period_seconds': int(SystemSetting.get_value('qr_token_grace_period_seconds', 60) or 60)
|
||||
}
|
||||
|
||||
return {
|
||||
'status': 'success',
|
||||
'settings': {
|
||||
@@ -883,7 +888,8 @@ def get_all_settings(current_user: User = Depends(require_roles(["ADMIN"]))):
|
||||
'moodle': moodle_config,
|
||||
'ui': ui_config,
|
||||
'ai': ai_config,
|
||||
'ai_assistant': ai_config
|
||||
'ai_assistant': ai_config,
|
||||
'security_qr': security_qr
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1076,6 +1082,64 @@ async def update_ui_settings(
|
||||
}
|
||||
|
||||
|
||||
@admin_router.post("/settings/security-qr")
|
||||
@admin_router.post("/admin/settings/security-qr")
|
||||
async def update_security_qr_settings(
|
||||
request: Request,
|
||||
current_user: User = Depends(require_roles(["ADMIN"]))
|
||||
):
|
||||
"""Actualiza la configuración de rotación y validez de las credenciales QR dinámicas."""
|
||||
data = await get_request_payload(request)
|
||||
try:
|
||||
renewal_sec = int(data.get('renewal_interval_seconds', 3) or 3)
|
||||
except (ValueError, TypeError):
|
||||
renewal_sec = 3
|
||||
|
||||
try:
|
||||
grace_sec = int(data.get('grace_period_seconds', 60) or 60)
|
||||
except (ValueError, TypeError):
|
||||
grace_sec = 60
|
||||
|
||||
if renewal_sec < 1:
|
||||
renewal_sec = 1
|
||||
if renewal_sec > 300:
|
||||
renewal_sec = 300
|
||||
|
||||
if grace_sec < renewal_sec:
|
||||
grace_sec = renewal_sec * 5
|
||||
if grace_sec > 3600:
|
||||
grace_sec = 3600
|
||||
|
||||
SystemSetting.set_value(
|
||||
'qr_renewal_interval_seconds',
|
||||
str(renewal_sec),
|
||||
'Intervalo de renovación dinámica de QR (segundos)',
|
||||
category='security'
|
||||
)
|
||||
SystemSetting.set_value(
|
||||
'qr_token_grace_period_seconds',
|
||||
str(grace_sec),
|
||||
'Período de gracia y validez de tokens QR (segundos)',
|
||||
category='security'
|
||||
)
|
||||
|
||||
AuditService.log(
|
||||
action='UPDATE_SECURITY_QR_SETTINGS',
|
||||
module='settings',
|
||||
user=current_user,
|
||||
details=f"Parámetros QR actualizados: renovación={renewal_sec}s, gracia={grace_sec}s"
|
||||
)
|
||||
|
||||
return {
|
||||
'status': 'success',
|
||||
'message': f'Configuración de credenciales QR guardada: renovación cada {renewal_sec} segundos.',
|
||||
'security_qr': {
|
||||
'renewal_interval_seconds': renewal_sec,
|
||||
'grace_period_seconds': grace_sec
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@admin_router.post("/settings/ai")
|
||||
@admin_router.post("/admin/settings/ai")
|
||||
async def update_ai_settings(
|
||||
|
||||
@@ -6,6 +6,7 @@ from app import db
|
||||
from app.models.user import User
|
||||
from app.models.building import Building
|
||||
from app.models.access_log_qr import AccessLogQR
|
||||
from app.models.setting import SystemSetting
|
||||
from app.services.audit_service import AuditService
|
||||
from app.services.qr_security_service import QRSecurityService
|
||||
from dependencies import get_current_user, require_roles
|
||||
@@ -146,8 +147,12 @@ 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.
|
||||
"""
|
||||
token = QRSecurityService.generate_qr_token(current_user)
|
||||
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)
|
||||
|
||||
token = QRSecurityService.generate_qr_token(current_user, valid_seconds=grace_seconds)
|
||||
return {
|
||||
"status": "success",
|
||||
"qr_token": token,
|
||||
@@ -155,5 +160,7 @@ def get_my_credential_qr_token(
|
||||
"user_name": current_user.name,
|
||||
"user_dni": current_user.document_number,
|
||||
"user_role": (current_user.role or "ALUMNO").upper(),
|
||||
"expires_in_hours": QRSecurityService.DEFAULT_VALID_HOURS
|
||||
"expires_in_hours": QRSecurityService.DEFAULT_VALID_HOURS,
|
||||
"renewal_interval_seconds": renewal_seconds,
|
||||
"grace_period_seconds": grace_seconds
|
||||
}
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@ from setuptools import setup, find_packages
|
||||
|
||||
setup(
|
||||
name="edu-space-admin",
|
||||
version="3.8.45",
|
||||
version="3.8.46",
|
||||
description="Administrative interface for Edu-Space Classroom Management System (FastAPI ASGI Core)",
|
||||
author="Edu-Space Development Team",
|
||||
author_email="admin@edu-space.com",
|
||||
|
||||
@@ -229,6 +229,51 @@ def test_reception_my_qr_token_endpoint(init_database):
|
||||
assert data["status"] == "success"
|
||||
assert "qr_token" in data
|
||||
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
|
||||
|
||||
|
||||
def test_security_qr_settings_configuration(init_database):
|
||||
"""Verifica que el Administrador pueda configurar el tiempo de renovación desde Configuración Global."""
|
||||
client = TestClient(app)
|
||||
admin = _get_or_create_user("test_admin_qr_config@unicaba.edu.ar", "Admin General", "ADMIN")
|
||||
admin_tokens = JWTService.generate_tokens(admin)
|
||||
admin_headers = {"Authorization": f"Bearer {admin_tokens['access_token']}"}
|
||||
|
||||
# 1. Modificar parámetro a 5 segundos de rotación y 90 de gracia
|
||||
resp = client.post(
|
||||
"/api/v1/settings/security-qr",
|
||||
json={"renewal_interval_seconds": 5, "grace_period_seconds": 90},
|
||||
headers=admin_headers
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert data["status"] == "success"
|
||||
assert data["security_qr"]["renewal_interval_seconds"] == 5
|
||||
assert data["security_qr"]["grace_period_seconds"] == 90
|
||||
|
||||
# 2. Verificar que /settings/all reporte el nuevo valor
|
||||
all_resp = client.get("/api/v1/settings/all", headers=admin_headers)
|
||||
assert all_resp.status_code == 200
|
||||
all_settings = all_resp.json()["settings"]
|
||||
assert "security_qr" in all_settings
|
||||
assert all_settings["security_qr"]["renewal_interval_seconds"] == 5
|
||||
|
||||
# 3. Verificar que /reception/my-qr-token refleje los 5 segundos
|
||||
student = _get_or_create_user("test_student_renew@unicaba.edu.ar", "Martín Fierro", "ALUMNO")
|
||||
student_tokens = JWTService.generate_tokens(student)
|
||||
token_resp = client.get("/api/v1/reception/my-qr-token", headers={"Authorization": f"Bearer {student_tokens['access_token']}"})
|
||||
assert token_resp.status_code == 200
|
||||
assert token_resp.json()["renewal_interval_seconds"] == 5
|
||||
|
||||
# 4. Restaurar a 3 segundos (default)
|
||||
client.post(
|
||||
"/api/v1/settings/security-qr",
|
||||
json={"renewal_interval_seconds": 3, "grace_period_seconds": 60},
|
||||
headers=admin_headers
|
||||
)
|
||||
|
||||
|
||||
def test_live_context_benefit_search_integration(init_database):
|
||||
|
||||
Reference in New Issue
Block a user