fix(reception): eliminacion de fondos graficos invasivos y correccion definitiva en resolucion de DNI v3.8.56
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.55"
|
||||
__version__ = "3.8.56"
|
||||
|
||||
class DummyContext:
|
||||
def __enter__(self):
|
||||
|
||||
@@ -13,7 +13,11 @@ def limpiar_numero_documento(doc_raw: str) -> Tuple[str, Optional[str]]:
|
||||
if not doc_raw:
|
||||
return "", None
|
||||
doc_clean = doc_raw.strip()
|
||||
doc_sin_puntos = doc_clean.replace('.', '').replace(',', '').replace(' ', '')
|
||||
|
||||
# Limpiar prefijos comunes como 'DNI:', 'DNI ', 'D.N.I.:', 'D.N.I. ', 'DOC:', 'DOCUMENTO:'
|
||||
doc_clean = re.sub(r'^(?:DNI|D\.N\.I\.|DOC|DOCUMENTO)[\s\:\-\.]*', '', doc_clean, flags=re.IGNORECASE).strip()
|
||||
|
||||
doc_sin_puntos = doc_clean.replace('.', '').replace(',', '').replace(' ', '').replace('-', '')
|
||||
|
||||
# Patrón: Prefijo F o M seguido de 5 a 9 dígitos
|
||||
m = re.match(r'^([FMfm])(\d{5,9})$', doc_sin_puntos)
|
||||
@@ -42,8 +46,8 @@ def parsear_dni(raw_text: str) -> Dict[str, str]:
|
||||
# Limpiar terminadores y retornos de carro
|
||||
raw_clean = raw_text.strip().replace('\r', '').replace('\n', '')
|
||||
|
||||
# Algunos escáneres o formatos vienen separados por @, comillas simples ' o barras |
|
||||
text = raw_clean.replace('@', '"').replace("'", '"').replace('´', '"').replace('|', '"')
|
||||
# Algunos escáneres o formatos vienen separados por @, comillas simples ', barras | o punto y coma ;
|
||||
text = raw_clean.replace('@', '"').replace("'", '"').replace('´', '"').replace('|', '"').replace(';', '"')
|
||||
parts = text.split('"')
|
||||
|
||||
# Limpiar espacios de cada segmento
|
||||
|
||||
@@ -76,16 +76,29 @@ class QRSecurityService:
|
||||
|
||||
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("ñ", ":")
|
||||
# Normalizar prefijos de lectores ópticos en teclados con distribución en español:
|
||||
# Los lectores ópticos envían 'Ñ' en lugar de ':' en sistemas operativos con distribución en español cuando leen códigos UNICABA.
|
||||
clean_upper = clean.upper()
|
||||
if "UNICABAÑ" in clean_upper or "ÑUSRÑ" in clean_upper or "ÑDNIÑ" in clean_upper or clean_upper.startswith("USRÑ") or clean_upper.startswith("DNIÑ"):
|
||||
clean_normalized = clean.replace("Ñ", ":").replace("ñ", ":")
|
||||
else:
|
||||
clean_normalized = clean
|
||||
|
||||
# Si viene con prefijo UNICABA:QR:
|
||||
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:
|
||||
# 1. Intentar validar como JWT criptográfico institucional ÚNICAMENTE si tiene formato Base64URL de JWT
|
||||
# Un JWT institucional de UniCABA típicamente comienza con 'eyJ' o sus 3 segmentos son Base64URL puros
|
||||
is_potential_jwt = False
|
||||
if clean_normalized.startswith("eyJ") and clean_normalized.count(".") == 2:
|
||||
is_potential_jwt = True
|
||||
elif clean_normalized.count(".") == 2:
|
||||
jwt_parts = clean_normalized.split(".")
|
||||
if len(jwt_parts) == 3 and all(re.match(r'^[A-Za-z0-9_-]+$', p) for p in jwt_parts):
|
||||
is_potential_jwt = True
|
||||
|
||||
if is_potential_jwt:
|
||||
try:
|
||||
payload = jwt.decode(
|
||||
clean_normalized,
|
||||
@@ -93,24 +106,23 @@ class QRSecurityService:
|
||||
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."
|
||||
if payload.get("type") == cls.QR_TOKEN_TYPE:
|
||||
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."
|
||||
|
||||
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."
|
||||
|
||||
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."
|
||||
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)}"
|
||||
except jwt.PyJWTError:
|
||||
# Si falló la firma o decodificación, NO abortar: continuar con los métodos de DNI y fallback
|
||||
pass
|
||||
|
||||
# 2. Formatos fallback (cuando no es un JWT):
|
||||
# 2. Formatos fallback (DNI Argentino, USR:<id>, DNI:<doc> y entrada directa):
|
||||
# A. Intentar extraer patrón institucional UNICABA:USR:<id>
|
||||
usr_match = re.search(r"USR:(\d+)", clean_normalized)
|
||||
if usr_match:
|
||||
@@ -126,18 +138,23 @@ class QRSecurityService:
|
||||
pass
|
||||
|
||||
# B. Intentar extraer patrón institucional DNI:<doc>
|
||||
dni_match = re.search(r"DNI:([a-zA-Z0-9]+)", clean_normalized)
|
||||
dni_match = re.search(r"DNI:([a-zA-Z0-9\.\-]+)", clean_normalized, flags=re.IGNORECASE)
|
||||
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()
|
||||
raw_doc_match = dni_match.group(1).replace(".", "").replace("-", "").strip()
|
||||
if raw_doc_match and raw_doc_match.upper() != "NA":
|
||||
user_by_dni = User.query.filter(
|
||||
or_(
|
||||
User.document_number == raw_doc_match,
|
||||
func.replace(User.document_number, ".", "") == raw_doc_match
|
||||
)
|
||||
).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})."
|
||||
return user_by_dni, "AUTORIZADO", f"Identificación validada por documento de identidad (DNI {raw_doc_match})."
|
||||
|
||||
# C. Reconocimiento universal de DNI Argentino (Formatos Renaper 2009, 2012, 2026, Mi Argentina y PDF417 / QR)
|
||||
dni_info = parsear_dni(clean_normalized)
|
||||
dni_info = parsear_dni(clean_normalized) or parsear_dni(clean)
|
||||
if dni_info and dni_info.get("documento"):
|
||||
doc = dni_info["documento"].strip()
|
||||
doc_stripped = doc.lstrip("0") or doc
|
||||
@@ -152,6 +169,20 @@ class QRSecurityService:
|
||||
)
|
||||
).first()
|
||||
|
||||
# Resiliencia: si no se encontró por DNI exacto pero se extrajo nombre y apellido del DNI oficial
|
||||
if not user_by_dni and dni_info.get("apellido") and dni_info.get("nombre"):
|
||||
first_name = dni_info["nombre"].split()[0]
|
||||
user_by_dni = User.query.filter(
|
||||
User.name.ilike(f"%{dni_info['apellido']}%"),
|
||||
User.name.ilike(f"%{first_name}%")
|
||||
).first()
|
||||
if user_by_dni and not user_by_dni.document_number:
|
||||
try:
|
||||
user_by_dni.document_number = doc
|
||||
db.session.commit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if user_by_dni:
|
||||
if not user_by_dni.is_active:
|
||||
return user_by_dni, "RESTRINGIDO", f"Usuario inactivo en el sistema institucional (DNI {doc})."
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@ from setuptools import setup, find_packages
|
||||
|
||||
setup(
|
||||
name="edu-space-admin",
|
||||
version="3.8.55",
|
||||
version="3.8.56",
|
||||
description="Administrative interface for Edu-Space Classroom Management System (FastAPI ASGI Core)",
|
||||
author="Edu-Space Development Team",
|
||||
author_email="admin@edu-space.com",
|
||||
|
||||
@@ -145,3 +145,17 @@ def test_qr_security_service_resolves_dni_with_dots_and_stripping(app, init_data
|
||||
assert resolved.id == u.id
|
||||
assert st == "AUTORIZADO"
|
||||
|
||||
# Escanear con prefijo 'DNI: 45.123.456'
|
||||
res_prefixed, st_p, _ = QRSecurityService.decode_and_resolve_user('DNI: 45.123.456')
|
||||
assert res_prefixed is not None
|
||||
assert res_prefixed.id == u.id
|
||||
assert st_p == "AUTORIZADO"
|
||||
|
||||
# Escanear formato 2026 con fechas que contienen puntos (2 puntos en total: NO debe confundirse con JWT)
|
||||
token_with_dots = '00749743816@PUNTOS@ESTUDIANTE@45123456@G@09.02.89@23.04.26'
|
||||
res_dots, st_d, _ = QRSecurityService.decode_and_resolve_user(token_with_dots)
|
||||
assert res_dots is not None
|
||||
assert res_dots.id == u.id
|
||||
assert st_d == "AUTORIZADO"
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user