feat(qr): add 3-second dynamic QR auto-rotation and global settings configuration (v3.8.46)
This commit is contained in:
@@ -11,6 +11,22 @@ El formato está basado en [Keep a Changelog](https://keepachangelog.com/es-ES/1
|
|||||||
- **Sincronización Continua Moodle (Fase 6):** Automatización de workers persistentes en background para el procesamiento continuo de la cola de Web Services Moodle 4.1.
|
- **Sincronización Continua Moodle (Fase 6):** Automatización de workers persistentes en background para el procesamiento continuo de la cola de Web Services Moodle 4.1.
|
||||||
- **Pruebas de Carga y Hardening (Fase 6):** Pruebas de estrés de concurrencia y validación final de producción.
|
- **Pruebas de Carga y Hardening (Fase 6):** Pruebas de estrés de concurrencia y validación final de producción.
|
||||||
|
|
||||||
|
## [3.8.46] - 2026-10-28
|
||||||
|
### Added & Security (Rotación Dinámica de Código QR cada 3 Segundos y Configuración Global)
|
||||||
|
- **Rotación Dinámica de Código QR Anti-Captura (3 Segundos)**:
|
||||||
|
- Se implementó la renovación automática del código QR cada 3 segundos en el modal global (`user_qr_modal.html`), en el perfil de usuario (`profile.html`) y en la credencial completa (`card.html`).
|
||||||
|
- Se incorporó una barra de progreso animada con gradiente y contador en vivo en milisegundos que exhibe visualmente la rotación activa y la protección anti-screenshot / anti-fraude.
|
||||||
|
- El bucle de rotación se pausa automáticamente cuando el modal se cierra o la pestaña pasa a segundo plano (`visibilitychange`), optimizando recursos de red y CPU.
|
||||||
|
- **Configuración Global Parametrizada (`SystemSetting`)**:
|
||||||
|
- Se agregaron las variables de configuración `qr_renewal_interval_seconds` (por defecto: 3s) y `qr_token_grace_period_seconds` (por defecto: 60s) en backend `SystemSetting`.
|
||||||
|
- Se creó una nueva pestaña en el panel de Configuración Global (`/admin/settings` -> *Credencial QR & Acceso*) con formulario de ajuste, selector de accesos directos (3s, 5s, 10s, 30s) y explicación técnica de la ventana de gracia criptográfica.
|
||||||
|
- Endpoints expuestos: `POST /api/v1/settings/security-qr` y `GET /api/v1/settings/all`.
|
||||||
|
- **Servicio Criptográfico `QRSecurityService` y Endpoint de Recepción**:
|
||||||
|
- `QRSecurityService.generate_qr_token` ahora admite `valid_seconds`, generando un JWT firmado con identificador único (`jti`), marca temporal (`iat`) y ventana de expiración controlada por la configuración de gracia.
|
||||||
|
- El endpoint `/api/v1/reception/my-qr-token` entrega en su payload el parámetro `renewal_interval_seconds` para que los clientes web ajusten su ciclo de renovación de forma dinámica.
|
||||||
|
- **Suite de Pruebas Automatizadas**:
|
||||||
|
- Se incorporaron pruebas unitarias y de integración en `tests/test_benefits_and_reception.py` verificando la entrega del parámetro y la actualización de los valores de configuración en caliente (118/118 pruebas superadas con éxito).
|
||||||
|
|
||||||
## [3.8.45] - 2026-10-28
|
## [3.8.45] - 2026-10-28
|
||||||
### Added & UX (Acceso Global a Credencial Digital QR y Código QR Dinámico en Perfil de Usuario)
|
### Added & UX (Acceso Global a Credencial Digital QR y Código QR Dinámico en Perfil de Usuario)
|
||||||
- **Botón Global de Acceso a Credencial QR (`qr-credential-btn`)**:
|
- **Botón Global de Acceso a Credencial QR (`qr-credential-btn`)**:
|
||||||
|
|||||||
@@ -9,11 +9,11 @@ Memoria del proyecto entre sesiones para la rama `dev`.
|
|||||||
- Libro de Calificaciones (*Gradebook*) con actas de regularidad inmutables.
|
- Libro de Calificaciones (*Gradebook*) con actas de regularidad inmutables.
|
||||||
- Autenticación híbrida (Google OAuth 2.0, Moodle SSO, Local) y Modo Impersonación.
|
- Autenticación híbrida (Google OAuth 2.0, Moodle SSO, Local) y Modo Impersonación.
|
||||||
- Reinicialización segura del sistema con contraseña de Administrador.
|
- Reinicialización segura del sistema con contraseña de Administrador.
|
||||||
- **Sprint Activo: Acceso Global a Credencial Digital QR y Código QR Dinámico en Perfil (v3.8.45)**:
|
- **Sprint Activo: Rotación Dinámica de Código QR (3s) y Configuración Global (v3.8.46)**:
|
||||||
- **Botón Global QR junto al Botón de Tema**: Incorporación del botón `.qr-credential-btn` en el footer del sidebar (`sidebar-footer`) y en la cabecera móvil (`mobile-header`), abriendo el modal `#userQrCredentialModal` para visualización y regeneración inmediata de la credencial QR del usuario.
|
- **Rotación Dinámica de Código QR Anti-Captura (3 Segundos)**: Renovación automática del código QR cada 3 segundos en el modal global (`user_qr_modal.html`), en el perfil de usuario (`profile.html`) y en el carnet completo (`card.html`) con barra de progreso animada y contador en vivo.
|
||||||
- **Código QR Dinámico en Perfil (`/auth/profile`)**: Tarjeta destacada de Credencial Universitaria con renderizado de QR firmado, datos de DNI, rol y renovación interactiva en tiempo real.
|
- **Configuración Global Parametrizada (`SystemSetting`)**: Variables `qr_renewal_interval_seconds` (default 3s) y `qr_token_grace_period_seconds` (default 60s) configurables en el panel de Configuración Global (`/admin/settings` -> *Credencial QR & Acceso*) y respaldadas por `POST /api/v1/settings/security-qr`.
|
||||||
- **Endpoint BFF `/credential/token`**: Endpoint en Express para provisión de tokens criptográficos firmados con HMAC y tiempo de validez de 72hs.
|
- **Criptografía y Recepción**: `QRSecurityService.generate_qr_token` con soporte de `valid_seconds`, payload dinámico en `/api/v1/reception/my-qr-token` y 118/118 tests automatizados pasando exitosamente.
|
||||||
- **Versión Consolidada**: `v3.8.45`.
|
- **Versión Consolidada**: `v3.8.46`.
|
||||||
|
|
||||||
## Decisiones (y por qué)
|
## Decisiones (y por qué)
|
||||||
- **Flujo Secuencial de Bedelía (9 Pasos)**: Estandarizar la carga operativa en: 1) Sede -> 2) Aula -> 3) Ciclo Lectivo -> 4) Carrera -> 5) Materia (vinculada a Carrera) -> 6) Comisión (asociada a Materia, Carrera y Ciclo) -> 7) Profesores -> 8) Alumnos -> 9) Reserva de Espacio. Esto asegura consistencia e integridad relacional.
|
- **Flujo Secuencial de Bedelía (9 Pasos)**: Estandarizar la carga operativa en: 1) Sede -> 2) Aula -> 3) Ciclo Lectivo -> 4) Carrera -> 5) Materia (vinculada a Carrera) -> 6) Comisión (asociada a Materia, Carrera y Ciclo) -> 7) Profesores -> 8) Alumnos -> 9) Reserva de Espacio. Esto asegura consistencia e integridad relacional.
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ from typing import Any
|
|||||||
from database import db, get_db, engine, SessionLocal, session
|
from database import db, get_db, engine, SessionLocal, session
|
||||||
from config.config import Config
|
from config.config import Config
|
||||||
|
|
||||||
__version__ = "3.8.45"
|
__version__ = "3.8.46"
|
||||||
|
|
||||||
class DummyContext:
|
class DummyContext:
|
||||||
def __enter__(self):
|
def __enter__(self):
|
||||||
|
|||||||
@@ -32,12 +32,19 @@ class QRSecurityService:
|
|||||||
return getattr(Config, 'SECRET_KEY', 'unicaba-secret-qr-key')
|
return getattr(Config, 'SECRET_KEY', 'unicaba-secret-qr-key')
|
||||||
|
|
||||||
@classmethod
|
@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.
|
Emite un token JWT firmado de credencial institucional para el usuario.
|
||||||
Contiene identificación, rol, DNI y tiempo de expiración.
|
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)
|
now = datetime.now(timezone.utc)
|
||||||
|
exp_delta = timedelta(seconds=valid_seconds) if valid_seconds is not None else timedelta(hours=hours_valid)
|
||||||
payload = {
|
payload = {
|
||||||
"sub": str(user.id),
|
"sub": str(user.id),
|
||||||
"dni": user.document_number or "",
|
"dni": user.document_number or "",
|
||||||
@@ -46,7 +53,7 @@ class QRSecurityService:
|
|||||||
"type": cls.QR_TOKEN_TYPE,
|
"type": cls.QR_TOKEN_TYPE,
|
||||||
"jti": str(uuid.uuid4())[:8],
|
"jti": str(uuid.uuid4())[:8],
|
||||||
"iat": now,
|
"iat": now,
|
||||||
"exp": now + timedelta(hours=hours_valid)
|
"exp": now + exp_delta
|
||||||
}
|
}
|
||||||
return jwt.encode(payload, cls._get_secret(), algorithm="HS256")
|
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)
|
'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 {
|
return {
|
||||||
'status': 'success',
|
'status': 'success',
|
||||||
'settings': {
|
'settings': {
|
||||||
@@ -883,7 +888,8 @@ def get_all_settings(current_user: User = Depends(require_roles(["ADMIN"]))):
|
|||||||
'moodle': moodle_config,
|
'moodle': moodle_config,
|
||||||
'ui': ui_config,
|
'ui': ui_config,
|
||||||
'ai': ai_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("/settings/ai")
|
||||||
@admin_router.post("/admin/settings/ai")
|
@admin_router.post("/admin/settings/ai")
|
||||||
async def update_ai_settings(
|
async def update_ai_settings(
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ from app import db
|
|||||||
from app.models.user import User
|
from app.models.user import User
|
||||||
from app.models.building import Building
|
from app.models.building import Building
|
||||||
from app.models.access_log_qr import AccessLogQR
|
from app.models.access_log_qr import AccessLogQR
|
||||||
|
from app.models.setting import SystemSetting
|
||||||
from app.services.audit_service import AuditService
|
from app.services.audit_service import AuditService
|
||||||
from app.services.qr_security_service import QRSecurityService
|
from app.services.qr_security_service import QRSecurityService
|
||||||
from dependencies import get_current_user, require_roles
|
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
|
Genera y entrega el token criptográfico del código QR para la credencial digital
|
||||||
del usuario autenticado (estudiante o docente).
|
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 {
|
return {
|
||||||
"status": "success",
|
"status": "success",
|
||||||
"qr_token": token,
|
"qr_token": token,
|
||||||
@@ -155,5 +160,7 @@ def get_my_credential_qr_token(
|
|||||||
"user_name": current_user.name,
|
"user_name": current_user.name,
|
||||||
"user_dni": current_user.document_number,
|
"user_dni": current_user.document_number,
|
||||||
"user_role": (current_user.role or "ALUMNO").upper(),
|
"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(
|
setup(
|
||||||
name="edu-space-admin",
|
name="edu-space-admin",
|
||||||
version="3.8.45",
|
version="3.8.46",
|
||||||
description="Administrative interface for Edu-Space Classroom Management System (FastAPI ASGI Core)",
|
description="Administrative interface for Edu-Space Classroom Management System (FastAPI ASGI Core)",
|
||||||
author="Edu-Space Development Team",
|
author="Edu-Space Development Team",
|
||||||
author_email="admin@edu-space.com",
|
author_email="admin@edu-space.com",
|
||||||
|
|||||||
@@ -229,6 +229,51 @@ def test_reception_my_qr_token_endpoint(init_database):
|
|||||||
assert data["status"] == "success"
|
assert data["status"] == "success"
|
||||||
assert "qr_token" in data
|
assert "qr_token" in data
|
||||||
assert data["user_name"] == "Valeria Paz"
|
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):
|
def test_live_context_benefit_search_integration(init_database):
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "frontend",
|
"name": "frontend",
|
||||||
"version": "3.8.45",
|
"version": "3.8.46",
|
||||||
"description": "",
|
"description": "",
|
||||||
"main": "index.js",
|
"main": "index.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
|||||||
+3
-3
@@ -86,9 +86,9 @@ const env = nunjucks.configure(path.join(__dirname, '../views'), {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Versiones institucionales del sistema
|
// Versiones institucionales del sistema
|
||||||
const APP_VERSION = '3.8.45';
|
const APP_VERSION = '3.8.46';
|
||||||
const FRONTEND_VERSION = '3.8.45';
|
const FRONTEND_VERSION = '3.8.46';
|
||||||
const BACKEND_VERSION = '3.8.45';
|
const BACKEND_VERSION = '3.8.46';
|
||||||
|
|
||||||
env.addGlobal('app_version', APP_VERSION);
|
env.addGlobal('app_version', APP_VERSION);
|
||||||
env.addGlobal('frontend_version', FRONTEND_VERSION);
|
env.addGlobal('frontend_version', FRONTEND_VERSION);
|
||||||
|
|||||||
@@ -1794,6 +1794,10 @@ const handleGlobalSettings = async (req, res) => {
|
|||||||
}
|
}
|
||||||
if (settings) {
|
if (settings) {
|
||||||
settings.ui = settings.ui || { show_role_banner: true };
|
settings.ui = settings.ui || { show_role_banner: true };
|
||||||
|
settings.security_qr = settings.security_qr || {
|
||||||
|
renewal_interval_seconds: 3,
|
||||||
|
grace_period_seconds: 60
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -1893,6 +1897,7 @@ router.post('/settings/moodle/test', forwardSettingsAction);
|
|||||||
router.post('/settings/moodle/sync', forwardSettingsAction);
|
router.post('/settings/moodle/sync', forwardSettingsAction);
|
||||||
router.get('/settings/moodle/stats', forwardSettingsAction);
|
router.get('/settings/moodle/stats', forwardSettingsAction);
|
||||||
router.post('/settings/ui', forwardSettingsAction);
|
router.post('/settings/ui', forwardSettingsAction);
|
||||||
|
router.post('/settings/security-qr', forwardSettingsAction);
|
||||||
router.post('/settings/ai', forwardSettingsAction);
|
router.post('/settings/ai', forwardSettingsAction);
|
||||||
router.post('/settings/ai/test', forwardSettingsAction);
|
router.post('/settings/ai/test', forwardSettingsAction);
|
||||||
router.post('/settings/reset_system', forwardSettingsAction);
|
router.post('/settings/reset_system', forwardSettingsAction);
|
||||||
|
|||||||
@@ -7,12 +7,14 @@ router.use(requireAuth);
|
|||||||
router.get(['/my-card', '/', '/mi-credencial'], async (req, res) => {
|
router.get(['/my-card', '/', '/mi-credencial'], async (req, res) => {
|
||||||
let qrToken = '';
|
let qrToken = '';
|
||||||
let expiresInHours = 72;
|
let expiresInHours = 72;
|
||||||
|
let renewalIntervalSeconds = 3;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const resp = await req.apiClient.get('/reception/my-qr-token');
|
const resp = await req.apiClient.get('/reception/my-qr-token');
|
||||||
if (resp.data) {
|
if (resp.data) {
|
||||||
qrToken = resp.data.qr_token || '';
|
qrToken = resp.data.qr_token || '';
|
||||||
expiresInHours = resp.data.expires_in_hours || 72;
|
expiresInHours = resp.data.expires_in_hours || 72;
|
||||||
|
renewalIntervalSeconds = resp.data.renewal_interval_seconds || 3;
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.warn('QR token generation notice:', err.message);
|
console.warn('QR token generation notice:', err.message);
|
||||||
@@ -22,7 +24,8 @@ router.get(['/my-card', '/', '/mi-credencial'], async (req, res) => {
|
|||||||
title: 'Mi Credencial Digital — UniCABA',
|
title: 'Mi Credencial Digital — UniCABA',
|
||||||
user: req.user,
|
user: req.user,
|
||||||
qrToken,
|
qrToken,
|
||||||
expiresInHours
|
expiresInHours,
|
||||||
|
renewalIntervalSeconds
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -41,7 +44,8 @@ router.get('/token', async (req, res) => {
|
|||||||
user_name: req.user?.name || '',
|
user_name: req.user?.name || '',
|
||||||
user_dni: req.user?.document_number || '',
|
user_dni: req.user?.document_number || '',
|
||||||
user_role: (req.user?.role || 'ALUMNO').toUpperCase(),
|
user_role: (req.user?.role || 'ALUMNO').toUpperCase(),
|
||||||
expires_in_hours: 72
|
expires_in_hours: 72,
|
||||||
|
renewal_interval_seconds: 3
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -93,6 +93,11 @@
|
|||||||
<i class="bi bi-cpu me-2 text-success"></i>Asistente IA & LLM Local
|
<i class="bi bi-cpu me-2 text-success"></i>Asistente IA & LLM Local
|
||||||
</button>
|
</button>
|
||||||
</li>
|
</li>
|
||||||
|
<li class="nav-item" role="presentation">
|
||||||
|
<button class="nav-link" id="tab-security-qr-btn" data-bs-toggle="tab" data-bs-target="#tab-security-qr" type="button" role="tab">
|
||||||
|
<i class="bi bi-qr-code me-2 text-warning"></i>Credencial QR & Acceso
|
||||||
|
</button>
|
||||||
|
</li>
|
||||||
<li class="nav-item" role="presentation">
|
<li class="nav-item" role="presentation">
|
||||||
<button class="nav-link text-danger" id="tab-maintenance-btn" data-bs-toggle="tab" data-bs-target="#tab-maintenance" type="button" role="tab">
|
<button class="nav-link text-danger" id="tab-maintenance-btn" data-bs-toggle="tab" data-bs-target="#tab-maintenance" type="button" role="tab">
|
||||||
<i class="bi bi-radioactive me-2 text-danger"></i>Mantenimiento & Reinicio
|
<i class="bi bi-radioactive me-2 text-danger"></i>Mantenimiento & Reinicio
|
||||||
@@ -718,7 +723,92 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- ========================================== -->
|
<!-- ========================================== -->
|
||||||
<!-- PESTAÑA 6: MANTENIMIENTO & REINICIO -->
|
<!-- PESTAÑA 6: CREDENCIAL QR & ACCESO (SDD-012)-->
|
||||||
|
<!-- ========================================== -->
|
||||||
|
<div class="tab-pane fade" id="tab-security-qr" role="tabpanel">
|
||||||
|
<div class="row g-4">
|
||||||
|
<div class="col-lg-8">
|
||||||
|
<form id="securityQrForm" onsubmit="saveSecurityQrConfig(event)">
|
||||||
|
<div class="card border shadow-none bg-body-tertiary p-3 mb-4 rounded-3">
|
||||||
|
<h6 class="fw-bold mb-3 d-flex align-items-center">
|
||||||
|
<i class="bi bi-shield-lock-fill text-warning me-2"></i>Rotación Dinámica de Código QR Anti-Captura
|
||||||
|
</h6>
|
||||||
|
|
||||||
|
<div class="mb-4">
|
||||||
|
<label class="form-label small fw-semibold text-body" for="qr_renewal_interval_seconds">
|
||||||
|
Tiempo de Renovación del Código QR en Pantalla (Segundos)
|
||||||
|
</label>
|
||||||
|
<div class="input-group input-group-sm mb-2" style="max-width: 260px;">
|
||||||
|
<span class="input-group-text"><i class="bi bi-stopwatch"></i></span>
|
||||||
|
<input type="number" class="form-control font-monospace text-center fw-bold" id="qr_renewal_interval_seconds" name="renewal_interval_seconds"
|
||||||
|
min="1" max="300" step="1"
|
||||||
|
value="{{ settings.security_qr.renewal_interval_seconds if (settings and settings.security_qr and settings.security_qr.renewal_interval_seconds) else 3 }}" required>
|
||||||
|
<span class="input-group-text">segundos</span>
|
||||||
|
</div>
|
||||||
|
<div class="d-flex gap-2 flex-wrap mb-2">
|
||||||
|
<button type="button" class="btn btn-xs btn-outline-secondary py-1 px-2 small" onclick="setQrIntervalPreset(3)">
|
||||||
|
<i class="bi bi-lightning-charge text-warning me-1"></i>3 seg (Predeterminado)
|
||||||
|
</button>
|
||||||
|
<button type="button" class="btn btn-xs btn-outline-secondary py-1 px-2 small" onclick="setQrIntervalPreset(5)">
|
||||||
|
5 seg
|
||||||
|
</button>
|
||||||
|
<button type="button" class="btn btn-xs btn-outline-secondary py-1 px-2 small" onclick="setQrIntervalPreset(10)">
|
||||||
|
10 seg
|
||||||
|
</button>
|
||||||
|
<button type="button" class="btn btn-xs btn-outline-secondary py-1 px-2 small" onclick="setQrIntervalPreset(30)">
|
||||||
|
30 seg
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div class="text-muted small">
|
||||||
|
Frecuencia con la que la aplicación regenera la imagen del QR y su token criptográfico firmado en el modal del usuario, carnet y perfil.
|
||||||
|
Un valor de <strong>3 segundos</strong> garantiza máxima seguridad anti-screenshot / anti-captura para evitar que los estudiantes se presten accesos.
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<hr class="opacity-25 my-3">
|
||||||
|
|
||||||
|
<div class="mb-3">
|
||||||
|
<label class="form-label small fw-semibold text-body" for="qr_token_grace_period_seconds">
|
||||||
|
Ventana de Gracia / Validez de Lectura del Token (Segundos)
|
||||||
|
</label>
|
||||||
|
<div class="input-group input-group-sm mb-2" style="max-width: 260px;">
|
||||||
|
<span class="input-group-text"><i class="bi bi-hourglass-split"></i></span>
|
||||||
|
<input type="number" class="form-control font-monospace text-center fw-bold" id="qr_token_grace_period_seconds" name="grace_period_seconds"
|
||||||
|
min="5" max="3600" step="5"
|
||||||
|
value="{{ settings.security_qr.grace_period_seconds if (settings and settings.security_qr and settings.security_qr.grace_period_seconds) else 60 }}" required>
|
||||||
|
<span class="input-group-text">segundos</span>
|
||||||
|
</div>
|
||||||
|
<div class="text-muted small">
|
||||||
|
Tiempo durante el cual el escáner de Recepción aceptará como válido un token QR recién generado (tolerancia a latencia de red, enfoque de cámara y lectura en torniquetes). Se recomienda entre 30 y 120 segundos.
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="d-flex justify-content-end">
|
||||||
|
<button type="submit" class="btn btn-primary btn-sm px-4" id="btnSaveSecurityQr">
|
||||||
|
<i class="bi bi-check2-circle me-1"></i>Guardar Configuración de Credencial QR
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Panel de Consejos / UX & Seguridad -->
|
||||||
|
<div class="col-lg-4">
|
||||||
|
<div class="card border-0 bg-warning-subtle text-warning-emphasis p-3 rounded-3 mb-3">
|
||||||
|
<h6 class="fw-bold mb-2"><i class="bi bi-shield-check me-1"></i>Credencial Dinámica Anti-Fraude</h6>
|
||||||
|
<p class="small mb-2">
|
||||||
|
Al renovar el código cada 3 segundos, las capturas de pantalla tomadas por alumnos quedan invalidadas en los puntos de acceso físico.
|
||||||
|
</p>
|
||||||
|
<p class="small mb-0">
|
||||||
|
Cada rotación genera un JWT con identificador único (JTI) y marca de tiempo firmada, garantizando trazabilidad y seguridad institucional.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- ========================================== -->
|
||||||
|
<!-- PESTAÑA 7: MANTENIMIENTO & REINICIO -->
|
||||||
<!-- ========================================== -->
|
<!-- ========================================== -->
|
||||||
<div class="tab-pane fade" id="tab-maintenance" role="tabpanel">
|
<div class="tab-pane fade" id="tab-maintenance" role="tabpanel">
|
||||||
<div class="row g-4">
|
<div class="row g-4">
|
||||||
@@ -1500,6 +1590,57 @@ async function testAiConnection() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// -------------------------------------------------------------
|
||||||
|
// Configuración de Credenciales QR Dinámicas y Rotación (SDD-012)
|
||||||
|
// -------------------------------------------------------------
|
||||||
|
function setQrIntervalPreset(sec) {
|
||||||
|
const input = document.getElementById('qr_renewal_interval_seconds');
|
||||||
|
if (input) input.value = sec;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function saveSecurityQrConfig(e) {
|
||||||
|
e.preventDefault();
|
||||||
|
const btn = document.getElementById('btnSaveSecurityQr');
|
||||||
|
const renewalInput = document.getElementById('qr_renewal_interval_seconds');
|
||||||
|
const graceInput = document.getElementById('qr_token_grace_period_seconds');
|
||||||
|
|
||||||
|
btn.disabled = true;
|
||||||
|
btn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>Guardando...';
|
||||||
|
|
||||||
|
const payload = {
|
||||||
|
renewal_interval_seconds: parseInt(renewalInput.value, 10) || 3,
|
||||||
|
grace_period_seconds: parseInt(graceInput.value, 10) || 60
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
let res = await fetch('/admin/settings/security-qr', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(payload)
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!res.ok && res.status === 404) {
|
||||||
|
res = await fetch('/api/v1/admin/settings/security-qr', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(payload)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = await res.json();
|
||||||
|
if (res.ok) {
|
||||||
|
showAlert(data.message || 'Configuración de credenciales QR guardada exitosamente.', 'success');
|
||||||
|
} else {
|
||||||
|
showAlert(data.message || 'Error al guardar configuración de QR.', 'danger');
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
showAlert('Error de comunicación: ' + err.message, 'danger');
|
||||||
|
} finally {
|
||||||
|
btn.disabled = false;
|
||||||
|
btn.innerHTML = '<i class="bi bi-check2-circle me-1"></i>Guardar Configuración de Credencial QR';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// -------------------------------------------------------------
|
// -------------------------------------------------------------
|
||||||
// Reinicialización Total del Sistema (Requiere Contraseña Admin)
|
// Reinicialización Total del Sistema (Requiere Contraseña Admin)
|
||||||
// -------------------------------------------------------------
|
// -------------------------------------------------------------
|
||||||
|
|||||||
@@ -73,8 +73,23 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="mt-2 text-muted small" style="font-size: 0.72rem;" id="profileQrValidity">
|
|
||||||
<i class="bi bi-clock-history me-1"></i>QR Dinámico renovable ({{ expiresInHours or 72 }}hs)
|
<!-- Barra de Progreso y Cuenta Regresiva de Renovación Dinámica -->
|
||||||
|
<div class="mt-2 mb-2 px-2" style="max-width: 220px; margin: 0 auto;">
|
||||||
|
<div class="progress" style="height: 4px; background-color: rgba(180, 62, 142, 0.15); border-radius: 4px;">
|
||||||
|
<div id="profileQrProgressBar" class="progress-bar" role="progressbar" style="width: 100%; background: linear-gradient(90deg, #4338CA, #B43E8E); transition: width 0.1s linear;"></div>
|
||||||
|
</div>
|
||||||
|
<div class="d-flex justify-content-between align-items-center mt-1 text-muted small" style="font-size: 0.70rem;">
|
||||||
|
<span class="d-flex align-items-center gap-1">
|
||||||
|
<span class="spinner-grow spinner-grow-sm text-success" style="width: 5px; height: 5px;" role="status"></span>
|
||||||
|
<span class="text-success fw-semibold">Anti-captura</span>
|
||||||
|
</span>
|
||||||
|
<span>Renueva en <strong id="profileQrCountdown" class="font-monospace text-primary">3s</strong></span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="mt-1 text-muted small" style="font-size: 0.72rem;" id="profileQrValidity">
|
||||||
|
<i class="bi bi-arrow-repeat me-1"></i>Código dinámico con rotación cada 3 seg
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="col-md-7 col-lg-8">
|
<div class="col-md-7 col-lg-8">
|
||||||
@@ -307,6 +322,11 @@
|
|||||||
<script>
|
<script>
|
||||||
(function() {
|
(function() {
|
||||||
var profileQrInstance = null;
|
var profileQrInstance = null;
|
||||||
|
var timerId = null;
|
||||||
|
var renewalInterval = 3; // Segundos (default 3s configurable)
|
||||||
|
var elapsedMs = 0;
|
||||||
|
var tickIntervalMs = 100;
|
||||||
|
var isFetching = false;
|
||||||
var initialToken = "{{ qrToken }}";
|
var initialToken = "{{ qrToken }}";
|
||||||
var fallbackToken = "UNICABA:USR:{{ user.id }}:DNI:{{ user.document_number or user.email }}";
|
var fallbackToken = "UNICABA:USR:{{ user.id }}:DNI:{{ user.document_number or user.email }}";
|
||||||
|
|
||||||
@@ -329,11 +349,27 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
window.refreshProfileQrCode = function() {
|
function updateProgressUi() {
|
||||||
var icon = document.getElementById('profileRefreshQrIcon');
|
var progressBar = document.getElementById('profileQrProgressBar');
|
||||||
|
var countdownEl = document.getElementById('profileQrCountdown');
|
||||||
|
var totalMs = renewalInterval * 1000;
|
||||||
|
var remainingMs = Math.max(0, totalMs - elapsedMs);
|
||||||
|
var pct = Math.max(0, Math.min(100, (remainingMs / totalMs) * 100));
|
||||||
|
|
||||||
|
if (progressBar) {
|
||||||
|
progressBar.style.width = pct + '%';
|
||||||
|
}
|
||||||
|
if (countdownEl) {
|
||||||
|
countdownEl.textContent = (remainingMs / 1000).toFixed(1) + 's';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function fetchNewToken(showSpinner) {
|
||||||
|
if (isFetching) return;
|
||||||
|
isFetching = true;
|
||||||
|
|
||||||
var container = document.getElementById('profileQrCodeDisplay');
|
var container = document.getElementById('profileQrCodeDisplay');
|
||||||
if (icon) icon.classList.add('spin-animation');
|
if (showSpinner && container && !profileQrInstance) {
|
||||||
if (container) {
|
|
||||||
container.innerHTML = '<div class="spinner-border text-primary spinner-border-sm" role="status"></div>';
|
container.innerHTML = '<div class="spinner-border text-primary spinner-border-sm" role="status"></div>';
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -341,31 +377,75 @@
|
|||||||
.then(function(res) { return res.json(); })
|
.then(function(res) { return res.json(); })
|
||||||
.then(function(data) {
|
.then(function(data) {
|
||||||
if (data && data.qr_token) {
|
if (data && data.qr_token) {
|
||||||
|
if (data.renewal_interval_seconds && data.renewal_interval_seconds > 0) {
|
||||||
|
renewalInterval = data.renewal_interval_seconds;
|
||||||
|
}
|
||||||
drawQR(data.qr_token);
|
drawQR(data.qr_token);
|
||||||
if (data.expires_in_hours) {
|
var valEl = document.getElementById('profileQrValidity');
|
||||||
var valEl = document.getElementById('profileQrValidity');
|
if (valEl) {
|
||||||
if (valEl) {
|
valEl.innerHTML = '<i class="bi bi-arrow-repeat me-1"></i>Código dinámico con rotación cada ' + renewalInterval + ' seg';
|
||||||
valEl.innerHTML = '<i class="bi bi-clock-history me-1"></i>QR Dinámico renovable (' + data.expires_in_hours + 'hs)';
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
drawQR(fallbackToken);
|
drawQR(fallbackToken);
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.catch(function(err) {
|
.catch(function(err) {
|
||||||
console.warn('Error refrescando token:', err);
|
console.warn('Error refrescando token en perfil:', err);
|
||||||
drawQR(fallbackToken);
|
drawQR(fallbackToken);
|
||||||
})
|
})
|
||||||
.finally(function() {
|
.finally(function() {
|
||||||
if (icon) {
|
isFetching = false;
|
||||||
setTimeout(function() { icon.classList.remove('spin-animation'); }, 700);
|
elapsedMs = 0;
|
||||||
}
|
updateProgressUi();
|
||||||
});
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function startLoop() {
|
||||||
|
stopLoop();
|
||||||
|
elapsedMs = 0;
|
||||||
|
updateProgressUi();
|
||||||
|
fetchNewToken(false);
|
||||||
|
|
||||||
|
timerId = setInterval(function() {
|
||||||
|
elapsedMs += tickIntervalMs;
|
||||||
|
updateProgressUi();
|
||||||
|
|
||||||
|
if (elapsedMs >= renewalInterval * 1000) {
|
||||||
|
elapsedMs = 0;
|
||||||
|
fetchNewToken(false);
|
||||||
|
}
|
||||||
|
}, tickIntervalMs);
|
||||||
|
}
|
||||||
|
|
||||||
|
function stopLoop() {
|
||||||
|
if (timerId) {
|
||||||
|
clearInterval(timerId);
|
||||||
|
timerId = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
window.refreshProfileQrCode = function() {
|
||||||
|
var icon = document.getElementById('profileRefreshQrIcon');
|
||||||
|
if (icon) icon.classList.add('spin-animation');
|
||||||
|
elapsedMs = 0;
|
||||||
|
fetchNewToken(false);
|
||||||
|
setTimeout(function() {
|
||||||
|
if (icon) icon.classList.remove('spin-animation');
|
||||||
|
}, 600);
|
||||||
};
|
};
|
||||||
|
|
||||||
document.addEventListener('DOMContentLoaded', function() {
|
document.addEventListener('DOMContentLoaded', function() {
|
||||||
var tokenToUse = (initialToken && initialToken.length > 10) ? initialToken : fallbackToken;
|
var tokenToUse = (initialToken && initialToken.length > 10) ? initialToken : fallbackToken;
|
||||||
drawQR(tokenToUse);
|
drawQR(tokenToUse);
|
||||||
|
startLoop();
|
||||||
|
|
||||||
|
document.addEventListener('visibilitychange', function() {
|
||||||
|
if (document.hidden) {
|
||||||
|
stopLoop();
|
||||||
|
} else {
|
||||||
|
startLoop();
|
||||||
|
}
|
||||||
|
});
|
||||||
});
|
});
|
||||||
})();
|
})();
|
||||||
</script>
|
</script>
|
||||||
|
|||||||
@@ -53,10 +53,24 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Código QR Institucional -->
|
<!-- Código QR Institucional -->
|
||||||
<div class="p-3 bg-white rounded-4 shadow-sm d-inline-block mb-3" style="min-width: 200px; min-height: 200px;">
|
<div class="p-3 bg-white rounded-4 shadow-sm d-inline-block mb-2" style="min-width: 200px; min-height: 200px;">
|
||||||
<div id="qrcode" class="d-flex justify-content-center align-items-center"></div>
|
<div id="qrcode" class="d-flex justify-content-center align-items-center"></div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- Barra de Progreso y Cuenta Regresiva de Renovación Dinámica -->
|
||||||
|
<div class="mb-3 px-3" style="max-width: 240px; margin: 0 auto;">
|
||||||
|
<div class="progress" style="height: 4px; background-color: rgba(255, 255, 255, 0.2); border-radius: 4px;">
|
||||||
|
<div id="cardQrProgressBar" class="progress-bar bg-white" role="progressbar" style="width: 100%; transition: width 0.1s linear;"></div>
|
||||||
|
</div>
|
||||||
|
<div class="d-flex justify-content-between align-items-center mt-1 text-white-50 small" style="font-size: 0.70rem;">
|
||||||
|
<span class="d-flex align-items-center gap-1">
|
||||||
|
<span class="spinner-grow spinner-grow-sm text-success" style="width: 5px; height: 5px;" role="status"></span>
|
||||||
|
<span class="text-white fw-semibold">Anti-captura activo</span>
|
||||||
|
</span>
|
||||||
|
<span class="text-white">Renueva en <strong id="cardQrCountdown" class="font-monospace text-white">3s</strong></span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div class="d-flex justify-content-center align-items-center gap-3 text-start small opacity-90 mb-2">
|
<div class="d-flex justify-content-center align-items-center gap-3 text-start small opacity-90 mb-2">
|
||||||
<div>
|
<div>
|
||||||
<span class="d-block text-uppercase" style="font-size: 0.65rem;">Documento</span>
|
<span class="d-block text-uppercase" style="font-size: 0.65rem;">Documento</span>
|
||||||
@@ -72,8 +86,8 @@
|
|||||||
|
|
||||||
<!-- Footer de la Credencial -->
|
<!-- Footer de la Credencial -->
|
||||||
<div class="p-3 bg-black bg-opacity-25 border-top border-white border-opacity-10 d-flex align-items-center justify-content-between text-white-50 small">
|
<div class="p-3 bg-black bg-opacity-25 border-top border-white border-opacity-10 d-flex align-items-center justify-content-between text-white-50 small">
|
||||||
<span><i class="bi bi-clock-history me-1"></i> QR renovable</span>
|
<span id="cardRenewalText"><i class="bi bi-arrow-repeat me-1"></i> QR dinámico ({{ renewalIntervalSeconds or 3 }}s)</span>
|
||||||
<span>Validez: {{ expiresInHours }}hs</span>
|
<span>Validez institucional</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -104,16 +118,23 @@
|
|||||||
<!-- Librería QRCode.js via CDN -->
|
<!-- Librería QRCode.js via CDN -->
|
||||||
<script src="https://cdn.jsdelivr.net/npm/qrcodejs@1.0.0/qrcode.min.js"></script>
|
<script src="https://cdn.jsdelivr.net/npm/qrcodejs@1.0.0/qrcode.min.js"></script>
|
||||||
<script>
|
<script>
|
||||||
document.addEventListener('DOMContentLoaded', function() {
|
(function() {
|
||||||
const qrContainer = document.getElementById('qrcode');
|
var qrInstance = null;
|
||||||
const token = "{{ qrToken }}";
|
var timerId = null;
|
||||||
const fallbackText = "UNICABA:USR:{{ user.id }}:DNI:{{ user.document_number or user.email }}";
|
var renewalInterval = parseInt("{{ renewalIntervalSeconds or 3 }}", 10) || 3;
|
||||||
|
var elapsedMs = 0;
|
||||||
const textToEncode = token && token.length > 10 ? token : fallbackText;
|
var tickIntervalMs = 100;
|
||||||
|
var isFetching = false;
|
||||||
|
var initialToken = "{{ qrToken }}";
|
||||||
|
var fallbackText = "UNICABA:USR:{{ user.id }}:DNI:{{ user.document_number or user.email }}";
|
||||||
|
|
||||||
|
function drawQR(text) {
|
||||||
|
var qrContainer = document.getElementById('qrcode');
|
||||||
|
if (!qrContainer) return;
|
||||||
|
qrContainer.innerHTML = '';
|
||||||
try {
|
try {
|
||||||
new QRCode(qrContainer, {
|
qrInstance = new QRCode(qrContainer, {
|
||||||
text: textToEncode,
|
text: text,
|
||||||
width: 180,
|
width: 180,
|
||||||
height: 180,
|
height: 180,
|
||||||
colorDark: "#0F172A",
|
colorDark: "#0F172A",
|
||||||
@@ -124,6 +145,90 @@
|
|||||||
console.error('Error generando QR:', e);
|
console.error('Error generando QR:', e);
|
||||||
qrContainer.innerHTML = '<div class="alert alert-warning p-2 small">Código disponible en modo texto</div>';
|
qrContainer.innerHTML = '<div class="alert alert-warning p-2 small">Código disponible en modo texto</div>';
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateProgressUi() {
|
||||||
|
var progressBar = document.getElementById('cardQrProgressBar');
|
||||||
|
var countdownEl = document.getElementById('cardQrCountdown');
|
||||||
|
var totalMs = renewalInterval * 1000;
|
||||||
|
var remainingMs = Math.max(0, totalMs - elapsedMs);
|
||||||
|
var pct = Math.max(0, Math.min(100, (remainingMs / totalMs) * 100));
|
||||||
|
|
||||||
|
if (progressBar) {
|
||||||
|
progressBar.style.width = pct + '%';
|
||||||
|
}
|
||||||
|
if (countdownEl) {
|
||||||
|
countdownEl.textContent = (remainingMs / 1000).toFixed(1) + 's';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function fetchNewToken() {
|
||||||
|
if (isFetching) return;
|
||||||
|
isFetching = true;
|
||||||
|
|
||||||
|
fetch('/credential/token')
|
||||||
|
.then(function(res) { return res.json(); })
|
||||||
|
.then(function(data) {
|
||||||
|
if (data && data.qr_token) {
|
||||||
|
if (data.renewal_interval_seconds && data.renewal_interval_seconds > 0) {
|
||||||
|
renewalInterval = data.renewal_interval_seconds;
|
||||||
|
}
|
||||||
|
drawQR(data.qr_token);
|
||||||
|
var textEl = document.getElementById('cardRenewalText');
|
||||||
|
if (textEl) {
|
||||||
|
textEl.innerHTML = '<i class="bi bi-arrow-repeat me-1"></i> QR dinámico (' + renewalInterval + 's)';
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
drawQR(fallbackText);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(function(err) {
|
||||||
|
console.warn('Error renovando QR de carnet:', err);
|
||||||
|
drawQR(fallbackText);
|
||||||
|
})
|
||||||
|
.finally(function() {
|
||||||
|
isFetching = false;
|
||||||
|
elapsedMs = 0;
|
||||||
|
updateProgressUi();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function startLoop() {
|
||||||
|
stopLoop();
|
||||||
|
elapsedMs = 0;
|
||||||
|
updateProgressUi();
|
||||||
|
|
||||||
|
timerId = setInterval(function() {
|
||||||
|
elapsedMs += tickIntervalMs;
|
||||||
|
updateProgressUi();
|
||||||
|
|
||||||
|
if (elapsedMs >= renewalInterval * 1000) {
|
||||||
|
elapsedMs = 0;
|
||||||
|
fetchNewToken();
|
||||||
|
}
|
||||||
|
}, tickIntervalMs);
|
||||||
|
}
|
||||||
|
|
||||||
|
function stopLoop() {
|
||||||
|
if (timerId) {
|
||||||
|
clearInterval(timerId);
|
||||||
|
timerId = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
document.addEventListener('DOMContentLoaded', function() {
|
||||||
|
var textToEncode = (initialToken && initialToken.length > 10) ? initialToken : fallbackText;
|
||||||
|
drawQR(textToEncode);
|
||||||
|
startLoop();
|
||||||
|
|
||||||
|
document.addEventListener('visibilitychange', function() {
|
||||||
|
if (document.hidden) {
|
||||||
|
stopLoop();
|
||||||
|
} else {
|
||||||
|
startLoop();
|
||||||
|
}
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
})();
|
||||||
</script>
|
</script>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|||||||
@@ -53,6 +53,20 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- Barra de Progreso y Cuenta Regresiva de Renovación Dinámica -->
|
||||||
|
<div class="mt-2 mb-2 px-3" style="max-width: 260px; margin: 0 auto;">
|
||||||
|
<div class="progress" style="height: 4px; background-color: rgba(180, 62, 142, 0.15); border-radius: 4px;">
|
||||||
|
<div id="modalQrProgressBar" class="progress-bar" role="progressbar" style="width: 100%; background: linear-gradient(90deg, #4338CA, #B43E8E); transition: width 0.1s linear;"></div>
|
||||||
|
</div>
|
||||||
|
<div class="d-flex justify-content-between align-items-center mt-1 text-muted small" style="font-size: 0.72rem;">
|
||||||
|
<span class="d-flex align-items-center gap-1">
|
||||||
|
<span class="spinner-grow spinner-grow-sm text-success" style="width: 6px; height: 6px;" role="status"></span>
|
||||||
|
<span class="text-success fw-semibold">Anti-captura activo</span>
|
||||||
|
</span>
|
||||||
|
<span>Renueva en <strong id="modalQrCountdown" class="font-monospace text-primary">3s</strong></span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<!-- Información de Validez y Seguridad -->
|
<!-- Información de Validez y Seguridad -->
|
||||||
<div class="mt-2 mb-3">
|
<div class="mt-2 mb-3">
|
||||||
<div class="d-inline-flex align-items-center gap-1 text-success small fw-semibold">
|
<div class="d-inline-flex align-items-center gap-1 text-success small fw-semibold">
|
||||||
@@ -60,7 +74,7 @@
|
|||||||
<span>Firma Criptográfica Verificada</span>
|
<span>Firma Criptográfica Verificada</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="text-muted small mt-1" style="font-size: 0.73rem;" id="modalQrValidityText">
|
<div class="text-muted small mt-1" style="font-size: 0.73rem;" id="modalQrValidityText">
|
||||||
<i class="bi bi-clock-history me-1"></i>QR Dinámico renovable cada 72hs
|
<i class="bi bi-arrow-repeat me-1"></i>Código dinámico con rotación cada 3 seg
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -68,7 +82,7 @@
|
|||||||
<div class="d-grid gap-2">
|
<div class="d-grid gap-2">
|
||||||
<div class="btn-group">
|
<div class="btn-group">
|
||||||
<button type="button" class="btn btn-outline-secondary btn-sm py-2" onclick="refreshGlobalQrModal()" id="btnRefreshGlobalQr">
|
<button type="button" class="btn btn-outline-secondary btn-sm py-2" onclick="refreshGlobalQrModal()" id="btnRefreshGlobalQr">
|
||||||
<i class="bi bi-arrow-clockwise me-1" id="globalRefreshQrIcon"></i>Actualizar Código QR
|
<i class="bi bi-arrow-clockwise me-1" id="globalRefreshQrIcon"></i>Rotar Ahora
|
||||||
</button>
|
</button>
|
||||||
<a href="/credential/my-card" class="btn btn-primary btn-sm py-2">
|
<a href="/credential/my-card" class="btn btn-primary btn-sm py-2">
|
||||||
<i class="bi bi-person-badge me-1"></i>Ver Carnet Completo
|
<i class="bi bi-person-badge me-1"></i>Ver Carnet Completo
|
||||||
@@ -93,7 +107,11 @@
|
|||||||
<script>
|
<script>
|
||||||
(function() {
|
(function() {
|
||||||
let qrModalInstance = null;
|
let qrModalInstance = null;
|
||||||
let cachedQrToken = null;
|
let timerId = null;
|
||||||
|
let renewalInterval = 3; // Segundos (default 3s configurable)
|
||||||
|
let elapsedMs = 0;
|
||||||
|
const tickIntervalMs = 100;
|
||||||
|
let isFetching = false;
|
||||||
|
|
||||||
function ensureQrLibrary(callback) {
|
function ensureQrLibrary(callback) {
|
||||||
if (typeof QRCode !== 'undefined') {
|
if (typeof QRCode !== 'undefined') {
|
||||||
@@ -132,16 +150,27 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function loadAndRenderQR(forceRefresh) {
|
function updateProgressUi() {
|
||||||
var spinner = document.getElementById('globalQrSpinner');
|
var progressBar = document.getElementById('modalQrProgressBar');
|
||||||
var container = document.getElementById('globalQrModalContainer');
|
var countdownEl = document.getElementById('modalQrCountdown');
|
||||||
|
var totalMs = renewalInterval * 1000;
|
||||||
|
var remainingMs = Math.max(0, totalMs - elapsedMs);
|
||||||
|
var pct = Math.max(0, Math.min(100, (remainingMs / totalMs) * 100));
|
||||||
|
|
||||||
if (!forceRefresh && cachedQrToken) {
|
if (progressBar) {
|
||||||
renderModalQR(cachedQrToken);
|
progressBar.style.width = pct + '%';
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
if (countdownEl) {
|
||||||
|
countdownEl.textContent = (remainingMs / 1000).toFixed(1) + 's';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (container && (!qrModalInstance || forceRefresh)) {
|
function fetchAndRenderToken(showSpinner) {
|
||||||
|
if (isFetching) return;
|
||||||
|
isFetching = true;
|
||||||
|
|
||||||
|
var container = document.getElementById('globalQrModalContainer');
|
||||||
|
if (showSpinner && container && !qrModalInstance) {
|
||||||
container.innerHTML = '<div class="spinner-border text-primary spinner-border-sm" role="status"></div>';
|
container.innerHTML = '<div class="spinner-border text-primary spinner-border-sm" role="status"></div>';
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -149,15 +178,15 @@
|
|||||||
.then(function(res) { return res.json(); })
|
.then(function(res) { return res.json(); })
|
||||||
.then(function(data) {
|
.then(function(data) {
|
||||||
if (data && data.qr_token) {
|
if (data && data.qr_token) {
|
||||||
cachedQrToken = data.qr_token;
|
if (data.renewal_interval_seconds && data.renewal_interval_seconds > 0) {
|
||||||
|
renewalInterval = data.renewal_interval_seconds;
|
||||||
|
}
|
||||||
ensureQrLibrary(function() {
|
ensureQrLibrary(function() {
|
||||||
renderModalQR(data.qr_token);
|
renderModalQR(data.qr_token);
|
||||||
});
|
});
|
||||||
if (data.expires_in_hours) {
|
var valText = document.getElementById('modalQrValidityText');
|
||||||
var valText = document.getElementById('modalQrValidityText');
|
if (valText) {
|
||||||
if (valText) {
|
valText.innerHTML = '<i class="bi bi-arrow-repeat me-1"></i>Código dinámico con rotación cada ' + renewalInterval + ' seg';
|
||||||
valText.innerHTML = '<i class="bi bi-clock-history me-1"></i>QR Dinámico renovable cada ' + data.expires_in_hours + 'hs';
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
throw new Error('Token no disponible');
|
throw new Error('Token no disponible');
|
||||||
@@ -169,23 +198,56 @@
|
|||||||
ensureQrLibrary(function() {
|
ensureQrLibrary(function() {
|
||||||
renderModalQR(fallback);
|
renderModalQR(fallback);
|
||||||
});
|
});
|
||||||
|
})
|
||||||
|
.finally(function() {
|
||||||
|
isFetching = false;
|
||||||
|
elapsedMs = 0;
|
||||||
|
updateProgressUi();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function startAutoRefreshLoop() {
|
||||||
|
stopAutoRefreshLoop();
|
||||||
|
elapsedMs = 0;
|
||||||
|
updateProgressUi();
|
||||||
|
fetchAndRenderToken(false);
|
||||||
|
|
||||||
|
timerId = setInterval(function() {
|
||||||
|
elapsedMs += tickIntervalMs;
|
||||||
|
updateProgressUi();
|
||||||
|
|
||||||
|
if (elapsedMs >= renewalInterval * 1000) {
|
||||||
|
elapsedMs = 0;
|
||||||
|
fetchAndRenderToken(false);
|
||||||
|
}
|
||||||
|
}, tickIntervalMs);
|
||||||
|
}
|
||||||
|
|
||||||
|
function stopAutoRefreshLoop() {
|
||||||
|
if (timerId) {
|
||||||
|
clearInterval(timerId);
|
||||||
|
timerId = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
window.refreshGlobalQrModal = function() {
|
window.refreshGlobalQrModal = function() {
|
||||||
var icon = document.getElementById('globalRefreshQrIcon');
|
var icon = document.getElementById('globalRefreshQrIcon');
|
||||||
if (icon) icon.classList.add('spin-animation');
|
if (icon) icon.classList.add('spin-animation');
|
||||||
loadAndRenderQR(true);
|
elapsedMs = 0;
|
||||||
|
fetchAndRenderToken(false);
|
||||||
setTimeout(function() {
|
setTimeout(function() {
|
||||||
if (icon) icon.classList.remove('spin-animation');
|
if (icon) icon.classList.remove('spin-animation');
|
||||||
}, 800);
|
}, 600);
|
||||||
};
|
};
|
||||||
|
|
||||||
document.addEventListener('DOMContentLoaded', function() {
|
document.addEventListener('DOMContentLoaded', function() {
|
||||||
var modalEl = document.getElementById('userQrCredentialModal');
|
var modalEl = document.getElementById('userQrCredentialModal');
|
||||||
if (modalEl) {
|
if (modalEl) {
|
||||||
modalEl.addEventListener('show.bs.modal', function() {
|
modalEl.addEventListener('show.bs.modal', function() {
|
||||||
loadAndRenderQR(false);
|
startAutoRefreshLoop();
|
||||||
|
});
|
||||||
|
modalEl.addEventListener('hide.bs.modal', function() {
|
||||||
|
stopAutoRefreshLoop();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user