Bloqueo de cuenta y config. resumen

This commit is contained in:
2025-05-29 15:47:42 -06:00
parent e08a813802
commit e17577dbd8
4 changed files with 181 additions and 41 deletions

View File

@@ -544,49 +544,50 @@ function verificarCodigo()
sqlsrv_free_stmt($stmt);
if (!$row) {
echo json_encode(['success' => false, 'message' => '❌ Código no encontrado o ya usado.']);
exit;
}
// Manejo de intentos fallidos en sesión
if (!isset($_SESSION['intentos_codigo'])) {
$_SESSION['intentos_codigo'] = 0;
}
$_SESSION['intentos_codigo']++;
// Verificar si se han excedido los intentos
if ($_SESSION['intentos_codigo'] >= 5) {
// Bloquear el código en la base de datos
$sqlUpdate = "UPDATE recuperacion_password SET estatus = 1 WHERE id = ?";
$stmtUpdate = sqlsrv_query($conn, $sqlUpdate, [$row['id']]);
if ($stmtUpdate) {
sqlsrv_free_stmt($stmtUpdate);
}
// 🚨 ENVIAR NOTIFICACIÓN DE SEGURIDAD
try {
enviarNotificacionIntentosExcedidos($email);
} catch (Exception $e) {
error_log("❌ Error al enviar notificación de intentos excedidos: " . $e->getMessage());
}
// Limpiar sesión
unset($_SESSION['intentos_codigo']);
unset($_SESSION['email_recuperacion']);
echo json_encode([
'success' => false,
'message' => '🚫 Has excedido el número de intentos permitidos. Por seguridad, se ha bloqueado el código. Solicita uno nuevo.',
'blocked' => true
'success' => false,
'message' => '🚫 Has excedido el número de intentos permitidos. Tu cuenta ha sido bloqueada por seguridad. Contacta a tu agente aduanal.',
'blocked' => true,
'redirect' => '/IMPORTADORES/login'
]);
exit;
}
// Manejo de intentos fallidos en sesión
if (!isset($_SESSION['intentos_codigo']) || !is_numeric($_SESSION['intentos_codigo'])) {
$_SESSION['intentos_codigo'] = 0;
}
// Compara códigos - asegurando que no haya problemas con mayúsculas o espacios
if (strcasecmp($codigo, $row['codigo']) !== 0) {
$intentosRestantes = 5 - $_SESSION['intentos_codigo'];
$_SESSION['intentos_codigo']++; // ⬅️ Incrementa solo si es incorrecto
$intentosRestantes = max(0, 5 - $_SESSION['intentos_codigo']);
// Verificar si se han excedido los intentos
if ($_SESSION['intentos_codigo'] >= 5) {
// Bloquear el código
$sqlUpdate = "UPDATE recuperacion_password SET estatus = 1 WHERE id = ?";
$stmtUpdate = sqlsrv_query($conn, $sqlUpdate, [$row['id']]);
if ($stmtUpdate) sqlsrv_free_stmt($stmtUpdate);
// Bloquear la cuenta del usuario
$sqlBloquearUsuario = "UPDATE usuarios_sistema SET activo = 0 WHERE email = ?";
$stmtBloqueo = sqlsrv_query($conn, $sqlBloquearUsuario, [$emailEncrypted]);
if ($stmtBloqueo) sqlsrv_free_stmt($stmtBloqueo);
// Enviar notificación
try {
enviarNotificacionCuentaBloqueada($email);
enviarNotificacionIntentosExcedidos($email);
} catch (Exception $e) {
error_log("❌ Error al enviar notificación de cuenta bloqueada: " . $e->getMessage());
error_log("❌ Error al enviar notificación de intentos excedidos: " . $e->getMessage());
}
unset($_SESSION['intentos_codigo']);
unset($_SESSION['email_recuperacion']);
}
echo json_encode([
'success' => false,
'message' => "❌ Código incorrecto. Te quedan {$intentosRestantes} intentos.",
@@ -819,6 +820,87 @@ function enviarNotificacionSeguridadIntentos($emailDestino, $nombreUsuario, $dat
}
}
/** Función para enviar el email de notificación de cuenta bloqueado **/
function enviarNotificacionCuentaBloqueada($email, $esCorreoAdicional = false)
{
$conn = getConnection();
if (!$conn) throw new Exception("No se pudo conectar a la base de datos");
$emailEncrypted = encrypt($email);
$sqlNotif = "SELECT nombre, email FROM usuarios_sistema WHERE email = ?";
$stmt = sqlsrv_query($conn, $sqlNotif, [$emailEncrypted]);
if (!$stmt) throw new Exception("Error al consultar información del usuario");
$usuario = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
sqlsrv_free_stmt($stmt);
if (!$usuario) {
error_log("⚠️ Usuario no encontrado para enviar notificación de cuenta bloqueada");
return false;
}
$usuario['email'] = decrypt($usuario['email']);
$usuario['nombre'] = decrypt($usuario['nombre']);
$mail = new PHPMailer(true);
$mail->isSMTP();
$mail->Host = 'secure.emailsrvr.com';
$mail->SMTPAuth = true;
$mail->Username = 'noreply@aduanasoft.com.mx';
$mail->Password = $_ENV['SMTP_PASS'];
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->Port = 587;
// Configuración de correo
$mail->setFrom('noreply@aduanasoft.com.mx', 'SIIH | AduanaSoft');
$mail->addAddress($usuario['email']);
$mail->CharSet = 'UTF-8';
$mail->isHTML(true);
$asunto = "🚫 Cuenta Bloqueada por Seguridad";
$mail->Subject = $asunto;
$tipoCorreo = $esCorreoAdicional ? "(Correo Adicional)" : "";
$mail->Body = "
<html>
<head>
<meta charset='UTF-8'>
<title>Alerta de Seguridad</title>
</head>
<body style='font-family: Arial, sans-serif; line-height: 1.6; color: #333;'>
<div style='max-width: 600px; margin: 0 auto; padding: 20px; border: 1px solid #ddd; border-radius: 10px;'>
<div style='text-align: center; margin-bottom: 30px;'>
<h1 style='color: #dc3545; margin: 0;'>🚫 Cuenta Bloqueada</h1>
<p style='color: #666; margin: 5px 0;'>$tipoCorreo</p>
</div>
<hr>
<div style='background-color: #f8f9fa; padding: 20px; border-radius: 8px; margin-bottom: 20px;'>
<p>Hola <b>{$usuario['nombre']}</b>,</p>
<p>Tu cuenta ha sido bloqueada automáticamente tras 5 intentos fallidos al verificar tu código de recuperación.</p>
<p>Por seguridad, deberás contactar a tu agente aduanal para reactivar tu cuenta.</p>
<p>Fecha: <b>" . date('Y-m-d H:i:s') . "</b><br>
IP: <b>" . ($_SERVER['REMOTE_ADDR'] ?? 'Desconocida') . "</b></p>
</div>
<hr>
<div style='text-align: center; margin-top: 30px; padding-top: 20px; border-top: 1px solid #eee;'>
<p style='color: #666; font-size: 12px; margin: 0;'>
Esta es una notificación automática de seguridad.<br>
Si tienes preguntas, contacta a nuestro equipo de soporte.
</p>
</div>
</div>
</body>
</html>";
$mail->send();
error_log("✅ Notificación de cuenta bloqueada enviada a: {$usuario['email']}");
return true;
}
function cambiarPasswordVista()
{
if (!isset($_SESSION['recuperacion_autorizada'])) {