231 lines
10 KiB
Python
231 lines
10 KiB
Python
import re
|
|
import hmac
|
|
import hashlib
|
|
import json
|
|
import base64
|
|
import uuid
|
|
from datetime import datetime, timedelta, timezone, date
|
|
from typing import Dict, Any, Optional, Tuple, List
|
|
import jwt
|
|
|
|
from config.config import Config
|
|
from app import db
|
|
from app.models.user import User
|
|
from app.models.reservation import Reservation
|
|
from app.models.classroom import Classroom
|
|
from app.models.building import Building
|
|
from app.models.enrollment import StudentEnrollment
|
|
from app.models.subject import Commission, Subject
|
|
from schemas.reception_dto import TodayClassDTO
|
|
|
|
|
|
class QRSecurityService:
|
|
"""
|
|
Servicio de emisión, validación criptográfica y resolución académica para
|
|
la Credencial Digital y el Control de Acceso por QR en Recepción (SDD-012).
|
|
"""
|
|
|
|
QR_TOKEN_TYPE = "credential_qr"
|
|
DEFAULT_VALID_HOURS = 72
|
|
|
|
@classmethod
|
|
def _get_secret(cls) -> str:
|
|
return getattr(Config, 'SECRET_KEY', 'unicaba-secret-qr-key')
|
|
|
|
@classmethod
|
|
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 "",
|
|
"name": user.name or "",
|
|
"role": (user.role or "ALUMNO").upper(),
|
|
"type": cls.QR_TOKEN_TYPE,
|
|
"jti": str(uuid.uuid4())[:8],
|
|
"iat": now,
|
|
"exp": now + exp_delta
|
|
}
|
|
return jwt.encode(payload, cls._get_secret(), algorithm="HS256")
|
|
|
|
@classmethod
|
|
def decode_and_resolve_user(cls, raw_input: str) -> Tuple[Optional[User], str, str]:
|
|
"""
|
|
Decodifica y valida el token escaneado. Soporta:
|
|
1. Token JWT firmado institucional.
|
|
2. Formato prefijado 'UNICABA:QR:<token>' (o con 'Ñ' por pistola en teclado español).
|
|
3. Formato institucional por ID o DNI 'UNICABA:USR:<id>:DNI:<doc>' (o 'UNICABAÑUSRÑ<id>ÑDNIÑ<doc>').
|
|
4. Formato fallback por DNI 'DNI:<documento>' o número de documento directo.
|
|
|
|
Retorna: (User or None, status: 'AUTORIZADO' | 'DENEGADO' | 'RESTRINGIDO', reason: str)
|
|
"""
|
|
if not raw_input or not raw_input.strip():
|
|
return None, "DENEGADO", "El código escaneado está vacío."
|
|
|
|
clean = raw_input.strip()
|
|
|
|
# Normalizar pistola óptica en teclado en español:
|
|
# Los lectores ópticos emulan teclado US, por lo que envían 'Ñ' en lugar de ':' en sistemas operativos con distribución en español.
|
|
clean_normalized = clean.replace("Ñ", ":").replace("ñ", ":")
|
|
|
|
# Si viene con prefijo UNICABA:QR:
|
|
if clean_normalized.startswith("UNICABA:QR:"):
|
|
clean_normalized = clean_normalized[len("UNICABA:QR:"):].strip()
|
|
|
|
# A. Intentar extraer patrón institucional UNICABA:USR:<id>
|
|
usr_match = re.search(r"USR:(\d+)", clean_normalized)
|
|
if usr_match:
|
|
try:
|
|
u_id = int(usr_match.group(1))
|
|
if u_id > 0:
|
|
user_by_id = User.query.get(u_id)
|
|
if user_by_id:
|
|
if not user_by_id.is_active:
|
|
return user_by_id, "RESTRINGIDO", "Usuario inactivo o suspendido en el sistema institucional."
|
|
return user_by_id, "AUTORIZADO", f"Credencial institucional validada por ID #{user_by_id.id}."
|
|
except Exception:
|
|
pass
|
|
|
|
# B. Intentar extraer patrón institucional DNI:<doc>
|
|
dni_match = re.search(r"DNI:([a-zA-Z0-9]+)", clean_normalized)
|
|
if dni_match:
|
|
doc = dni_match.group(1).strip()
|
|
if doc and doc.upper() != "N/A":
|
|
user_by_dni = User.query.filter_by(document_number=doc).first()
|
|
if user_by_dni:
|
|
if not user_by_dni.is_active:
|
|
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:"):
|
|
doc_num = doc_num[4:].strip()
|
|
|
|
# Quitar cualquier carácter residual no alfanumérico si es número de DNI
|
|
clean_doc = re.sub(r'[^a-zA-Z0-9]', '', doc_num)
|
|
if clean_doc:
|
|
user = User.query.filter_by(document_number=clean_doc).first()
|
|
if not user and clean_doc.isdigit():
|
|
# Si no coincide con documento, verificar si coincide con ID institucional directo
|
|
user = User.query.get(int(clean_doc))
|
|
|
|
if user:
|
|
if not user.is_active:
|
|
return user, "RESTRINGIDO", "Usuario inactivo en el sistema institucional."
|
|
return user, "AUTORIZADO", f"Identificación validada por documento de identidad ({user.document_number or user.id})."
|
|
|
|
return None, "DENEGADO", f"No se encontró ningún estudiante o docente con DNI o credencial '{raw_input.strip()}'."
|
|
|
|
@classmethod
|
|
def get_todays_classes_for_user(cls, user: User, target_date: Optional[date] = None) -> List[TodayClassDTO]:
|
|
"""
|
|
Recupera el cronograma presencial y virtual asignado para el usuario en la fecha indicada (por defecto hoy).
|
|
Indica sede, aula física, piso, horarios y nombre del docente.
|
|
"""
|
|
ref_date = target_date or date.today()
|
|
user_role = (user.role or "").lower()
|
|
classes: List[TodayClassDTO] = []
|
|
|
|
start_of_day = datetime.combine(ref_date, datetime.min.time())
|
|
end_of_day = datetime.combine(ref_date, datetime.max.time())
|
|
|
|
# Si el usuario es docente: reservas donde él es el docente asignado
|
|
if "docente" in user_role or "profesor" in user_role or "teacher" in user_role:
|
|
reservations = Reservation.query.filter(
|
|
Reservation.user_id == user.id,
|
|
Reservation.start_time >= start_of_day,
|
|
Reservation.start_time <= end_of_day,
|
|
Reservation.status.in_(["CONFIRMED", "PENDING"])
|
|
).order_by(Reservation.start_time.asc()).all()
|
|
|
|
for r in reservations:
|
|
comm = r.commission
|
|
subj_name = comm.subject.name if (comm and comm.subject) else "Clase Universitaria"
|
|
comm_name = comm.name if comm else "Comisión"
|
|
classroom = r.classroom
|
|
bld = classroom.building_entity if classroom else None
|
|
|
|
classes.append(TodayClassDTO(
|
|
subject_name=subj_name,
|
|
commission_name=comm_name,
|
|
classroom_name=classroom.name if classroom else "Aula no asignada",
|
|
building_name=bld.name if bld else "Sede Central",
|
|
floor=getattr(classroom, "floor", 1),
|
|
start_time=r.start_time.strftime("%H:%M"),
|
|
end_time=r.end_time.strftime("%H:%M"),
|
|
teacher_name=user.name
|
|
))
|
|
return classes
|
|
|
|
# Si el usuario es alumno: comisiones donde está inscripto
|
|
enrollments = StudentEnrollment.query.filter_by(student_id=user.id).all()
|
|
comm_ids = [e.commission_id for e in enrollments if e.commission_id]
|
|
|
|
if not comm_ids:
|
|
return []
|
|
|
|
reservations = Reservation.query.filter(
|
|
Reservation.commission_id.in_(comm_ids),
|
|
Reservation.start_time >= start_of_day,
|
|
Reservation.start_time <= end_of_day,
|
|
Reservation.status.in_(["CONFIRMED", "PENDING"])
|
|
).order_by(Reservation.start_time.asc()).all()
|
|
|
|
for r in reservations:
|
|
comm = r.commission
|
|
subj_name = comm.subject.name if (comm and comm.subject) else "Materia Cursada"
|
|
comm_name = comm.name if comm else "Comisión"
|
|
classroom = r.classroom
|
|
bld = classroom.building_entity if classroom else None
|
|
teacher_name = r.user.name if r.user else "Docente Titular"
|
|
|
|
classes.append(TodayClassDTO(
|
|
subject_name=subj_name,
|
|
commission_name=comm_name,
|
|
classroom_name=classroom.name if classroom else "Aula no asignada",
|
|
building_name=bld.name if bld else "Sede Central",
|
|
floor=getattr(classroom, "floor", 1),
|
|
start_time=r.start_time.strftime("%H:%M"),
|
|
end_time=r.end_time.strftime("%H:%M"),
|
|
teacher_name=teacher_name
|
|
))
|
|
|
|
return classes
|