fix(reception): eliminacion de fondos graficos invasivos y correccion definitiva en resolucion de DNI v3.8.56
This commit is contained in:
@@ -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})."
|
||||
|
||||
Reference in New Issue
Block a user