Merge branch 'main' of https://github.com/AduanaSoft/IMPORTADORES
This commit is contained in:
@@ -165,6 +165,39 @@ function desvincularAgente()
|
||||
throw new Exception('Error al desactivar la relación: ' . print_r(sqlsrv_errors(), true));
|
||||
}
|
||||
|
||||
// NUEVO: Verificar si el importador desvinculado tenía esta agencia como activa
|
||||
$sqlVerificarAgenciaActiva = "
|
||||
SELECT id_agencia_en_uso
|
||||
FROM usuarios_sistema
|
||||
WHERE id_usuario = ? AND id_agencia_en_uso = ?
|
||||
";
|
||||
$stmtVerificarActiva = sqlsrv_query($conn, $sqlVerificarAgenciaActiva,
|
||||
[$relacion['id_importador'], $relacion['id_agencia']]);
|
||||
|
||||
if ($stmtVerificarActiva === false) {
|
||||
throw new Exception('Error al verificar agencia activa: ' . print_r(sqlsrv_errors(), true));
|
||||
}
|
||||
|
||||
if ($stmtVerificarActiva && sqlsrv_fetch_array($stmtVerificarActiva, SQLSRV_FETCH_ASSOC)) {
|
||||
// Si tenía esta agencia como activa, quitársela
|
||||
$sqlQuitarAgenciaActiva = "
|
||||
UPDATE usuarios_sistema
|
||||
SET id_agencia_en_uso = NULL
|
||||
WHERE id_usuario = ?
|
||||
";
|
||||
$stmtQuitarActiva = sqlsrv_query($conn, $sqlQuitarAgenciaActiva, [$relacion['id_importador']]);
|
||||
|
||||
if ($stmtQuitarActiva === false) {
|
||||
throw new Exception('Error al actualizar la agencia activa del importador: ' . print_r(sqlsrv_errors(), true));
|
||||
}
|
||||
}
|
||||
|
||||
// Limpiar statements
|
||||
sqlsrv_free_stmt($stmtVerificarActiva);
|
||||
if (isset($stmtQuitarActiva)) {
|
||||
sqlsrv_free_stmt($stmtQuitarActiva);
|
||||
}
|
||||
|
||||
// Confirmar transacción
|
||||
sqlsrv_commit($conn);
|
||||
|
||||
|
||||
@@ -102,7 +102,7 @@ function sistemaAgencia()
|
||||
include __DIR__ . '/../../views/bitacoras/sistema_agencia.php';
|
||||
}
|
||||
|
||||
function usuarios()
|
||||
function cambios()
|
||||
{
|
||||
if (!isset($_SESSION['usuario_id']) || $_SESSION['tipo_usuario'] !== 'super_admin') {
|
||||
header('Location: /IMPORTADORES/login');
|
||||
@@ -122,6 +122,32 @@ function usuarios()
|
||||
$registros[] = $row;
|
||||
}
|
||||
|
||||
include __DIR__ . '/../../views/bitacoras/bitacora_cambios.php';
|
||||
}
|
||||
|
||||
function usuarios()
|
||||
{
|
||||
if (!isset($_SESSION['usuario_id']) || $_SESSION['tipo_usuario'] !== 'super_admin') {
|
||||
header('Location: /IMPORTADORES/login');
|
||||
exit;
|
||||
}
|
||||
|
||||
$conn = getConnection();
|
||||
$sql = "SELECT u.*, creador.nombre AS nombre_creador
|
||||
FROM usuarios_sistema u
|
||||
LEFT JOIN usuarios_sistema creador ON u.creado_por = creador.id_usuario
|
||||
ORDER BY creado_en DESC";
|
||||
$stmt = sqlsrv_query($conn, $sql);
|
||||
|
||||
if ($stmt === false) {
|
||||
die(print_r(sqlsrv_errors(), true));
|
||||
}
|
||||
|
||||
$usuarios = [];
|
||||
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
|
||||
$usuarios[] = $row;
|
||||
}
|
||||
|
||||
include __DIR__ . '/../../views/bitacoras/bitacora_usuarios.php';
|
||||
}
|
||||
|
||||
|
||||
@@ -184,9 +184,26 @@ function desvincularUsuario()
|
||||
throw new Exception('No se pudo actualizar la relación');
|
||||
}
|
||||
|
||||
// 3. Actualizar el campo id_agencia_en_uso del usuario si es necesario
|
||||
if ($_SESSION['id_agencia_en_uso'] == $relacion['id_agencia']) {
|
||||
$sqlActualizarAgencia = "
|
||||
UPDATE usuarios_sistema
|
||||
SET id_agencia_en_uso = NULL
|
||||
WHERE id_usuario = ?
|
||||
";
|
||||
$stmtActualizarAgencia = sqlsrv_query($conn, $sqlActualizarAgencia, [$_SESSION['usuario_id']]);
|
||||
|
||||
if ($stmtActualizarAgencia === false) {
|
||||
$errors = sqlsrv_errors();
|
||||
error_log("Error al actualizar agencia en uso: " . print_r($errors, true));
|
||||
throw new Exception('Error al actualizar la agencia en uso');
|
||||
}
|
||||
}
|
||||
|
||||
// Limpiar statements
|
||||
sqlsrv_free_stmt($stmtVerificar);
|
||||
sqlsrv_free_stmt($stmtDesactivar);
|
||||
sqlsrv_free_stmt($stmtActualizarAgencia);
|
||||
|
||||
// Confirmar transacción
|
||||
sqlsrv_commit($conn);
|
||||
|
||||
505
app/controllers/reset.php
Normal file
505
app/controllers/reset.php
Normal file
@@ -0,0 +1,505 @@
|
||||
<?php
|
||||
require_once __DIR__ . '/../helpers/session.php';
|
||||
require_once __DIR__ . '/../../config/database.php';
|
||||
require_once __DIR__ . '/../helpers/crypto.php';
|
||||
require_once __DIR__ . '/../helpers/bitacoras.php';
|
||||
require_once __DIR__ . '/../helpers/env.php';
|
||||
|
||||
require_once __DIR__ . '/../../vendor/autoload.php';
|
||||
use PHPMailer\PHPMailer\PHPMailer;
|
||||
use PHPMailer\PHPMailer\Exception;
|
||||
|
||||
loadEnv();
|
||||
|
||||
function enviarCodigoInterno()
|
||||
{
|
||||
// header('Content-Type: application/json');
|
||||
|
||||
// Verificar que el usuario esté autenticado
|
||||
if (!isset($_SESSION['usuario_id']) || !isset($_SESSION['usuario_email'])) {
|
||||
echo json_encode(['success' => false, 'message' => '❌ Sesión no válida. Inicia sesión nuevamente.']);
|
||||
exit;
|
||||
}
|
||||
|
||||
$conn = getConnection();
|
||||
if (!$conn) {
|
||||
echo json_encode(['success' => false, 'message' => '❌ Error de conexión con la base de datos.']);
|
||||
exit;
|
||||
}
|
||||
|
||||
$id_usuario = $_SESSION['usuario_id'];
|
||||
$email = $_SESSION['usuario_email'];
|
||||
$emailEncrypted = encrypt($email);
|
||||
|
||||
// Verificar que la cuenta esté activa
|
||||
$sql = "SELECT activo FROM usuarios_sistema WHERE id_usuario = ?";
|
||||
$stmt = sqlsrv_query($conn, $sql, [$id_usuario]);
|
||||
|
||||
if (!$stmt || !($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))) {
|
||||
echo json_encode(['success' => false, 'message' => '❌ Usuario no encontrado.']);
|
||||
exit;
|
||||
}
|
||||
|
||||
if ($row['activo'] != 1) {
|
||||
echo json_encode(['success' => false, 'message' => '❌ Tu cuenta está inactiva.']);
|
||||
exit;
|
||||
}
|
||||
|
||||
// Verificar si ya existe un código activo
|
||||
$now = (new DateTime())->format('Y-m-d H:i:s');
|
||||
$sqlCheck = "SELECT COUNT(*) AS total FROM recuperacion_password
|
||||
WHERE email = ? AND estatus = 0 AND expiracion > ?";
|
||||
$checkStmt = sqlsrv_query($conn, $sqlCheck, [$emailEncrypted, $now]);
|
||||
$checkRow = sqlsrv_fetch_array($checkStmt, SQLSRV_FETCH_ASSOC);
|
||||
|
||||
if ($checkRow['total'] > 0) {
|
||||
echo json_encode(['success' => false, 'message' => '⚠️ Ya tienes un código activo. Revisa tu correo o espera 10 minutos.']);
|
||||
exit;
|
||||
}
|
||||
|
||||
// Generar nuevo código
|
||||
$codigo = strval(random_int(100000, 999999));
|
||||
$expira = (new DateTime('+10 minutes'))->format('Y-m-d H:i:s');
|
||||
$estatus = 0;
|
||||
|
||||
$insert = "INSERT INTO recuperacion_password (email, codigo, expiracion, estatus) VALUES (?, ?, ?, ?)";
|
||||
$params = [$emailEncrypted, $codigo, $expira, $estatus];
|
||||
$result = sqlsrv_query($conn, $insert, $params);
|
||||
|
||||
if (!$result) {
|
||||
echo json_encode(['success' => false, 'message' => '❌ Error al generar el código de verificación.']);
|
||||
exit;
|
||||
}
|
||||
|
||||
// Establecer variables de sesión para el cambio interno
|
||||
$_SESSION['cambio_interno'] = true;
|
||||
$_SESSION['codigo_timestamp'] = time();
|
||||
|
||||
// Agregar estos logs:
|
||||
error_log("DEBUG enviarCodigoInterno - SESSION después de establecer variables: " . print_r($_SESSION, true));
|
||||
error_log("DEBUG - cambio_interno establecido: " . ($_SESSION['cambio_interno'] ? 'TRUE' : 'FALSE'));
|
||||
|
||||
// Enviar código por correo
|
||||
try {
|
||||
$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;
|
||||
|
||||
$mail->setFrom('noreply@aduanasoft.com.mx', 'SIIH | AduanaSoft');
|
||||
$mail->addAddress($email);
|
||||
$mail->CharSet = 'UTF-8';
|
||||
$mail->isHTML(true);
|
||||
$mail->Subject = 'Código para cambio de contraseña';
|
||||
|
||||
$mail->Body = "
|
||||
<div style='font-family: Segoe UI, sans-serif; background-color: #f4f6f9; padding: 40px;'>
|
||||
<div style='max-width: 600px; margin: auto; background: #fff; border: 1px solid #ddd; border-radius: 10px; overflow: hidden;'>
|
||||
<div style='background: linear-gradient(to right, #003366, #0055A5); padding: 20px; text-align: center;'>
|
||||
<h2 style='color: white;'>Cambio de contraseña</h2>
|
||||
</div>
|
||||
<div style='padding: 30px; color: #333; font-size: 16px;'>
|
||||
<p>Has solicitado cambiar tu contraseña desde tu cuenta.</p>
|
||||
<div style='text-align: center; margin: 30px 0;'>
|
||||
<p>Tu código de verificación es:</p>
|
||||
<h2 style='color:#333; background: #f8f9fa; padding: 15px; border-radius: 8px; border: 2px dashed #0055A5;'>$codigo</h2>
|
||||
</div>
|
||||
<p>Este código expirará en 10 minutos.</p>
|
||||
<p><strong>Si no solicitaste este cambio, ignora este correo.</strong></p>
|
||||
</div>
|
||||
<div style='background: #e9ecef; text-align: center; padding: 15px; font-size: 13px; color: #666;'>
|
||||
© " . date('Y') . " SIIH · Sistema Integral para Importadores de Hidrocarburos
|
||||
</div>
|
||||
</div>
|
||||
</div>";
|
||||
|
||||
$mail->send();
|
||||
|
||||
// Redirigir directamente desde PHP
|
||||
header("Location: /IMPORTADORES/reset/verificarCodigoInternoView");
|
||||
exit;
|
||||
|
||||
} catch (Exception $e) {
|
||||
error_log("Error al enviar correo de cambio interno: {$mail->ErrorInfo}");
|
||||
|
||||
// Solo en caso de error, devolver JSON
|
||||
echo json_encode(['success' => false, 'message' => '❌ Error al enviar el correo. Intenta más tarde.']);
|
||||
exit;
|
||||
}
|
||||
}
|
||||
|
||||
function verificarCodigoInternoView()
|
||||
{
|
||||
// Verificar si el usuario ya está autenticado
|
||||
if (!isset($_SESSION['usuario_id']) || !isset($_SESSION['usuario_email']) || !isset($_SESSION['cambio_interno'])) {
|
||||
header("Location: /IMPORTADORES/login");
|
||||
exit;
|
||||
}
|
||||
|
||||
// Verificar si el código ya fue verificado
|
||||
if (isset($_SESSION['codigo_verificado_interno']) && $_SESSION['codigo_verificado_interno'] === true) {
|
||||
header("Location: /IMPORTADORES/reset/cambiarPasswordInternoView");
|
||||
exit;
|
||||
}
|
||||
|
||||
// Mostrar la vista de verificación de código interno
|
||||
include __DIR__ . '/../../views/reset/verificar_codigo.php';
|
||||
}
|
||||
|
||||
function verificarCodigoInterno()
|
||||
{
|
||||
header('Content-Type: application/json');
|
||||
|
||||
$conn = getConnection();
|
||||
|
||||
$email = $_SESSION['usuario_email'];
|
||||
$emailEncrypted = encrypt($email); // aplica aquí también
|
||||
|
||||
try {
|
||||
// Verificar conexión
|
||||
if (!isset($conn) || $conn === false) {
|
||||
echo json_encode([
|
||||
'success' => false,
|
||||
'message' => '❌ Error de conexión a la base de datos.',
|
||||
'intentos_restantes' => max(0, 3 - ($_SESSION['intentos_codigo_interno'] ?? 0))
|
||||
]);
|
||||
exit;
|
||||
}
|
||||
|
||||
$codigo = trim($_POST['codigo'] ?? '');
|
||||
|
||||
if (empty($codigo)) {
|
||||
echo json_encode([
|
||||
'success' => false,
|
||||
'message' => '❌ Código requerido.',
|
||||
'intentos_restantes' => max(0, 3 - ($_SESSION['intentos_codigo_interno'] ?? 0))
|
||||
]);
|
||||
exit;
|
||||
}
|
||||
|
||||
if (!preg_match('/^\d{6}$/', $codigo)) {
|
||||
echo json_encode([
|
||||
'success' => false,
|
||||
'message' => '❌ El código debe tener 6 dígitos numéricos.',
|
||||
'intentos_restantes' => max(0, 3 - ($_SESSION['intentos_codigo_interno'] ?? 0))
|
||||
]);
|
||||
exit;
|
||||
}
|
||||
|
||||
$intentosActuales = $_SESSION['intentos_codigo_interno'] ?? 0;
|
||||
|
||||
if ($intentosActuales >= 3) {
|
||||
echo json_encode([
|
||||
'success' => false,
|
||||
'message' => '❌ Demasiados intentos fallidos. Solicita un nuevo código.',
|
||||
'blocked' => true,
|
||||
'redirect' => '/IMPORTADORES/seguridad/index',
|
||||
'intentos_restantes' => 0
|
||||
]);
|
||||
exit;
|
||||
}
|
||||
|
||||
if (!isset($_SESSION['usuario_id']) || !isset($_SESSION['usuario_email'])) {
|
||||
echo json_encode([
|
||||
'success' => false,
|
||||
'message' => '❌ Sesión inválida. Intenta nuevamente.',
|
||||
'blocked' => true,
|
||||
'redirect' => '/IMPORTADORES/seguridad/index'
|
||||
]);
|
||||
exit;
|
||||
}
|
||||
|
||||
// Consulta principal para verificar el código
|
||||
$sql = "SELECT id, codigo, expiracion
|
||||
FROM recuperacion_password
|
||||
WHERE email = ? AND estatus = 0 AND expiracion > GETDATE()
|
||||
ORDER BY expiracion DESC
|
||||
";
|
||||
|
||||
$stmt = sqlsrv_query($conn, $sql, [$emailEncrypted]);
|
||||
|
||||
if (!$stmt) {
|
||||
throw new Exception("Error en la consulta a la base de datos");
|
||||
}
|
||||
|
||||
$row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
|
||||
sqlsrv_free_stmt($stmt);
|
||||
|
||||
if (!$row) {
|
||||
$_SESSION['intentos_codigo_interno'] = $intentosActuales + 1;
|
||||
echo json_encode([
|
||||
'success' => false,
|
||||
'message' => '❌ Código inválido o expirado.',
|
||||
'intentos_restantes' => max(0, 3 - $_SESSION['intentos_codigo_interno'])
|
||||
]);
|
||||
exit;
|
||||
}
|
||||
|
||||
if (!isset($row['codigo'], $row['id'], $row['expiracion'])) {
|
||||
throw new Exception("Faltan campos requeridos en la respuesta de la base de datos.");
|
||||
}
|
||||
|
||||
if ($codigo !== $row['codigo']) {
|
||||
$_SESSION['intentos_codigo_interno'] = $intentosActuales + 1;
|
||||
echo json_encode([
|
||||
'success' => false,
|
||||
'message' => '❌ Código incorrecto.',
|
||||
'intentos_restantes' => max(0, 3 - $_SESSION['intentos_codigo_interno'])
|
||||
]);
|
||||
exit;
|
||||
}
|
||||
|
||||
$expiracion = $row['expiracion'];
|
||||
$ahora = new DateTime();
|
||||
|
||||
if ($expiracion instanceof DateTime) {
|
||||
$expiracionStr = $expiracion->format('Y-m-d H:i:s');
|
||||
|
||||
if ($expiracion <= $ahora) {
|
||||
$_SESSION['intentos_codigo_interno'] = $intentosActuales + 1;
|
||||
echo json_encode([
|
||||
'success' => false,
|
||||
'message' => '❌ El código ha expirado.',
|
||||
'intentos_restantes' => max(0, 3 - $_SESSION['intentos_codigo_interno'])
|
||||
]);
|
||||
exit;
|
||||
}
|
||||
}
|
||||
|
||||
// Marcar el código como usado
|
||||
$sqlUpdate = "UPDATE recuperacion_password SET estatus = 1 WHERE id = ?";
|
||||
$stmtUpdate = sqlsrv_query($conn, $sqlUpdate, [$row['id']]);
|
||||
|
||||
if (!$stmtUpdate) {
|
||||
throw new Exception("Error al actualizar el estado del código");
|
||||
}
|
||||
|
||||
sqlsrv_free_stmt($stmtUpdate);
|
||||
|
||||
// Marcar como verificado y limpiar intentos
|
||||
$_SESSION['codigo_verificado_interno'] = true;
|
||||
unset($_SESSION['intentos_codigo_interno']);
|
||||
|
||||
echo json_encode([
|
||||
'success' => true,
|
||||
'message' => '✅ Código verificado correctamente.',
|
||||
'redirect' => '/IMPORTADORES/reset/cambiarPasswordInternoView'
|
||||
]);
|
||||
|
||||
} catch (Exception $e) {
|
||||
echo json_encode([
|
||||
'success' => false,
|
||||
'message' => '❌ Error interno del servidor. Intenta nuevamente.',
|
||||
'intentos_restantes' => max(0, 3 - ($_SESSION['intentos_codigo_interno'] ?? 0))
|
||||
]);
|
||||
exit;
|
||||
} finally {
|
||||
// Cerrar conexión si existe
|
||||
if (isset($conn) && $conn !== false) {
|
||||
sqlsrv_close($conn);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function cambiarPasswordInternoView()
|
||||
{
|
||||
// Verificar si el usuario ya está autenticado y el código verificado
|
||||
if (!isset($_SESSION['usuario_id']) || !isset($_SESSION['usuario_email']) ||
|
||||
!isset($_SESSION['cambio_interno']) || !isset($_SESSION['codigo_verificado_interno'])) {
|
||||
header("Location: /IMPORTADORES/login");
|
||||
exit;
|
||||
}
|
||||
|
||||
// Mostrar la vista de cambio de contraseña interno
|
||||
include __DIR__ . '/../../views/reset/change_password.php';
|
||||
}
|
||||
|
||||
function cambiarPasswordInterno()
|
||||
{
|
||||
header('Content-Type: application/json'); // ⬅️ AGREGAR ESTA LÍNEA
|
||||
|
||||
// Verificar autorización completa
|
||||
if (!isset($_SESSION['usuario_id']) || !isset($_SESSION['usuario_email']) ||
|
||||
!isset($_SESSION['cambio_interno']) || !isset($_SESSION['codigo_verificado_interno'])) {
|
||||
echo json_encode(['success' => false, 'message' => '❌ No tienes autorización para cambiar la contraseña.']);
|
||||
exit;
|
||||
}
|
||||
|
||||
$conn = getConnection();
|
||||
if (!$conn) {
|
||||
echo json_encode(['success' => false, 'message' => '❌ Error de conexión con la base de datos.']);
|
||||
exit;
|
||||
}
|
||||
|
||||
$passwordActual = $_POST['password_actual'] ?? '';
|
||||
$passwordNueva = $_POST['password_nueva'] ?? '';
|
||||
$confirmarPassword = $_POST['confirmar_password'] ?? '';
|
||||
|
||||
// Validaciones
|
||||
if (empty($passwordActual)) {
|
||||
echo json_encode(['success' => false, 'message' => '❌ La contraseña actual es requerida.']);
|
||||
exit;
|
||||
}
|
||||
|
||||
if (strlen($passwordNueva) < 6) {
|
||||
echo json_encode(['success' => false, 'message' => '❌ La nueva contraseña debe tener al menos 6 caracteres.']);
|
||||
exit;
|
||||
}
|
||||
|
||||
if ($passwordNueva !== $confirmarPassword) {
|
||||
echo json_encode(['success' => false, 'message' => '❌ Las contraseñas nuevas no coinciden.']);
|
||||
exit;
|
||||
}
|
||||
|
||||
if ($passwordActual === $passwordNueva) {
|
||||
echo json_encode(['success' => false, 'message' => '❌ La nueva contraseña debe ser diferente a la actual.']);
|
||||
exit;
|
||||
}
|
||||
|
||||
$id_usuario = $_SESSION['usuario_id'];
|
||||
$email = $_SESSION['usuario_email'];
|
||||
$emailEncrypted = encrypt($email);
|
||||
|
||||
// Verificar contraseña actual
|
||||
$sql = "SELECT password_hash FROM usuarios_sistema WHERE id_usuario = ?";
|
||||
$stmt = sqlsrv_query($conn, $sql, [$id_usuario]);
|
||||
|
||||
if (!$stmt || !($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))) {
|
||||
echo json_encode(['success' => false, 'message' => '❌ Error al verificar la contraseña actual.']);
|
||||
exit;
|
||||
}
|
||||
|
||||
if (!password_verify($passwordActual, $row['password_hash'])) {
|
||||
echo json_encode(['success' => false, 'message' => '❌ La contraseña actual es incorrecta.']);
|
||||
exit;
|
||||
}
|
||||
|
||||
// Actualizar contraseña
|
||||
$hashNueva = password_hash($passwordNueva, PASSWORD_BCRYPT);
|
||||
$sqlUpdate = "UPDATE usuarios_sistema SET password_hash = ? WHERE id_usuario = ?";
|
||||
$stmtUpdate = sqlsrv_prepare($conn, $sqlUpdate, [$hashNueva, $id_usuario]);
|
||||
|
||||
if (!$stmtUpdate || !sqlsrv_execute($stmtUpdate)) {
|
||||
echo json_encode(['success' => false, 'message' => '❌ Error al actualizar la contraseña.']);
|
||||
exit;
|
||||
}
|
||||
|
||||
// Registrar en bitácora
|
||||
$ip = $_SERVER['REMOTE_ADDR'] ?? 'N/A';
|
||||
registrarBitacora($conn, $id_usuario, $email, $ip, 1, 'Cambio de contraseña interno');
|
||||
|
||||
// Enviar correo de confirmación
|
||||
try {
|
||||
$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;
|
||||
|
||||
$mail->setFrom('noreply@aduanasoft.com.mx', 'SIIH | AduanaSoft');
|
||||
$mail->addAddress($email);
|
||||
$mail->CharSet = 'UTF-8';
|
||||
$mail->isHTML(true);
|
||||
$mail->Subject = 'Contraseña actualizada exitosamente';
|
||||
|
||||
$fechaHora = date('d/m/Y H:i:s');
|
||||
$mail->Body = "
|
||||
<div style='font-family: Segoe UI, sans-serif; background-color: #f4f6f9; padding: 40px;'>
|
||||
<div style='max-width: 600px; margin: auto; background: #fff; border: 1px solid #ddd; border-radius: 10px; overflow: hidden;'>
|
||||
<div style='background: linear-gradient(to right, #003366, #0055A5); padding: 20px; text-align: center;'>
|
||||
<h2 style='color: white;'>Contraseña actualizada</h2>
|
||||
</div>
|
||||
<div style='padding: 30px; color: #333; font-size: 16px;'>
|
||||
<p>Hola,</p>
|
||||
<p>Te confirmamos que tu contraseña ha sido <strong>cambiada exitosamente</strong> desde tu cuenta.</p>
|
||||
<p><strong>Fecha y hora:</strong> {$fechaHora}</p>
|
||||
<p><strong>IP:</strong> {$ip}</p>
|
||||
<div style='background: #fff3cd; border: 1px solid #ffeaa7; padding: 15px; border-radius: 5px; margin: 20px 0;'>
|
||||
<p style='margin: 0; color: #856404;'><strong>⚠️ Importante:</strong> Si no realizaste este cambio, contacta inmediatamente al área de soporte.</p>
|
||||
</div>
|
||||
</div>
|
||||
<div style='background: #e9ecef; text-align: center; padding: 15px; font-size: 13px; color: #666;'>
|
||||
© " . date('Y') . " SIIH · Sistema Integral para Importadores de Hidrocarburos
|
||||
</div>
|
||||
</div>
|
||||
</div>";
|
||||
|
||||
$mail->send();
|
||||
} catch (Exception $e) {
|
||||
error_log("Error al enviar correo de confirmación interno: {$mail->ErrorInfo}");
|
||||
// No fallar el proceso por error de email, solo registrar el error
|
||||
}
|
||||
|
||||
// Limpiar variables de sesión del proceso
|
||||
unset($_SESSION['cambio_interno']);
|
||||
unset($_SESSION['codigo_verificado_interno']);
|
||||
unset($_SESSION['codigo_timestamp']);
|
||||
|
||||
echo json_encode([
|
||||
'success' => true,
|
||||
'message' => '✅ Contraseña actualizada exitosamente.',
|
||||
'redirect' => '/IMPORTADORES/login' // Redirigir a la página de seguridad
|
||||
]);
|
||||
exit;
|
||||
}
|
||||
|
||||
function cancelarCambioInterno()
|
||||
{
|
||||
header('Content-Type: application/json');
|
||||
|
||||
if (isset($_SESSION['cambio_interno'])) {
|
||||
$conn = getConnection();
|
||||
|
||||
if ($conn && isset($_SESSION['usuario_email'])) {
|
||||
// Invalidar códigos activos
|
||||
$emailEncrypted = encrypt($_SESSION['usuario_email']);
|
||||
$sql = "UPDATE recuperacion_password SET estatus = 1 WHERE email = ? AND estatus = 0";
|
||||
$stmt = sqlsrv_query($conn, $sql, [$emailEncrypted]);
|
||||
if ($stmt) sqlsrv_free_stmt($stmt);
|
||||
}
|
||||
|
||||
// Limpiar sesión
|
||||
unset($_SESSION['cambio_interno']);
|
||||
unset($_SESSION['codigo_verificado_interno']);
|
||||
unset($_SESSION['intentos_codigo_interno']);
|
||||
unset($_SESSION['codigo_timestamp']);
|
||||
}
|
||||
|
||||
echo json_encode(['success' => true, 'message' => 'Proceso cancelado.']);
|
||||
}
|
||||
|
||||
// Función para obtener el estado actual (para mostrar en la vista)
|
||||
function obtenerEstadoDosFactores()
|
||||
{
|
||||
$conn = getConnection();
|
||||
|
||||
// CORRIGIDO: Cambiar id_usuario por usuario_id
|
||||
$id_usuario = $_SESSION['usuario_id'] ?? null;
|
||||
if (!$id_usuario) {
|
||||
return 0; // valor por defecto si no hay sesión
|
||||
}
|
||||
|
||||
$sql_dos_factores = "SELECT dos_factores FROM usuarios_sistema WHERE id_usuario = ?";
|
||||
$params = [$id_usuario];
|
||||
$stmt_dos_factores = sqlsrv_prepare($conn, $sql_dos_factores, $params);
|
||||
|
||||
$dos_factores_estado = 0; // valor por defecto
|
||||
|
||||
if ($stmt_dos_factores && sqlsrv_execute($stmt_dos_factores)) {
|
||||
if ($row = sqlsrv_fetch_array($stmt_dos_factores, SQLSRV_FETCH_ASSOC)) {
|
||||
$dos_factores_estado = (int)$row['dos_factores'];
|
||||
}
|
||||
}
|
||||
|
||||
sqlsrv_free_stmt($stmt_dos_factores);
|
||||
sqlsrv_close($conn);
|
||||
|
||||
return $dos_factores_estado;
|
||||
}
|
||||
@@ -439,15 +439,15 @@ function actualizar()
|
||||
// 3) Ejecutar UPDATE
|
||||
$sqlUpd = "UPDATE dbo.transportistas SET
|
||||
clave_identificador = ?,
|
||||
nombre = ?,
|
||||
rfc = ?,
|
||||
curp = ?,
|
||||
telefono = ?,
|
||||
caat = ?,
|
||||
pais = ?,
|
||||
entidad_federativa = ?,
|
||||
ciudad = ?,
|
||||
domicilio = ?
|
||||
nombre = ?,
|
||||
rfc = ?,
|
||||
curp = ?,
|
||||
telefono = ?,
|
||||
caat = ?,
|
||||
pais = ?,
|
||||
entidad_federativa = ?,
|
||||
ciudad = ?,
|
||||
domicilio = ?
|
||||
WHERE id_transportista = ?";
|
||||
$params = [
|
||||
$clave, $nombre, $rfc, $curp, $tel,
|
||||
|
||||
@@ -298,6 +298,32 @@ function desvincularAgencia()
|
||||
throw new Exception('Error al desactivar la relación de ' . $tipo);
|
||||
}
|
||||
|
||||
// NUEVO: Verificar si el usuario desvinculado tenía esta agencia como activa
|
||||
if ($tipo === 'importador') {
|
||||
// Verificar si el importador tenía esta agencia como activa
|
||||
$sqlVerificarAgenciaActiva = "
|
||||
SELECT id_agencia_en_uso
|
||||
FROM usuarios_sistema
|
||||
WHERE id_usuario = ? AND id_agencia_en_uso = ?
|
||||
";
|
||||
$stmtVerificarActiva = sqlsrv_query($conn, $sqlVerificarAgenciaActiva,
|
||||
[$relacion['id_importador'], $relacion['id_agencia']]);
|
||||
|
||||
if ($stmtVerificarActiva && sqlsrv_fetch_array($stmtVerificarActiva, SQLSRV_FETCH_ASSOC)) {
|
||||
// Si tenía esta agencia como activa, quitársela
|
||||
$sqlQuitarAgenciaActiva = "
|
||||
UPDATE usuarios_sistema
|
||||
SET id_agencia_en_uso = NULL
|
||||
WHERE id_usuario = ?
|
||||
";
|
||||
$stmtQuitarActiva = sqlsrv_query($conn, $sqlQuitarAgenciaActiva, [$relacion['id_importador']]);
|
||||
|
||||
if (!$stmtQuitarActiva) {
|
||||
throw new Exception('Error al actualizar la agencia activa del importador');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Confirmar transacción
|
||||
sqlsrv_commit($conn);
|
||||
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
<?php
|
||||
// Al inicio, antes de session_start() o donde manejes las sesiones
|
||||
ini_set('session.cookie_lifetime', 3600); // 1 hora
|
||||
ini_set('session.gc_maxlifetime', 3600);
|
||||
ini_set('session.cookie_httponly', 1);
|
||||
ini_set('session.use_only_cookies', 1);
|
||||
|
||||
if (session_status() === PHP_SESSION_NONE) {
|
||||
session_start();
|
||||
}
|
||||
|
||||
80
views/bitacoras/bitacora_cambios.php
Normal file
80
views/bitacoras/bitacora_cambios.php
Normal file
@@ -0,0 +1,80 @@
|
||||
<?php include __DIR__ . '/../partials/sidebar_configuracion.php'; ?>
|
||||
|
||||
<!DOCTYPE html>
|
||||
<html lang="es">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>🔄 Cambios de Usuario</title>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
|
||||
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
|
||||
<link href="https://cdn.datatables.net/1.13.4/css/jquery.dataTables.min.css" rel="stylesheet">
|
||||
<script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
|
||||
<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
|
||||
<style>
|
||||
body { font-family: 'Segoe UI', sans-serif; background-color: #f4f6f9; }
|
||||
.sidebar { width: 220px; height: 100vh; background-color: #343a40; position: fixed; top: 0; left: 0; padding-top: 56px; z-index: 1040; }
|
||||
.sidebar .nav-link { font-weight: normal; color: white; transition: all 0.3s ease; }
|
||||
.sidebar .nav-link:hover,
|
||||
.sidebar .nav-link.active { background-color: #495057; color: #fff; }
|
||||
.content { margin-top: 56px; padding: 40px 20px; position: relative; z-index: 1; background-color: #f4f6f9; transition: margin-left 0.3s ease; }
|
||||
.navbar { position: fixed; top: 0; width: 100%; z-index: 1050; }
|
||||
/* A partir de dispositivos medianos (>=768px), deja espacio lateral */
|
||||
@media (min-width: 768px) { .content { margin-left: 250px; /* Ancho del sidebar */ } }
|
||||
/* En móviles, sin margen lateral */
|
||||
@media (max-width: 767.98px) {
|
||||
.content { margin-left: 0; }
|
||||
.sidebar .nav-link { font-weight: normal; color: #343a40; background-color: transparent; }
|
||||
.sidebar .nav-link:hover,
|
||||
.sidebar .nav-link.active { background-color: #e9ecef; color: #212529; }
|
||||
}
|
||||
.card { border-radius: 12px; }
|
||||
.table thead th { background: #343a40; color: #fff; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<div class="content">
|
||||
<h4 class="mb-4">🔄 Cambios de Usuario</h4>
|
||||
|
||||
<div class="card p-3 shadow-sm">
|
||||
<div class="table-responsive">
|
||||
<table class="table table-striped align-middle" id="tabla-bitacora-usuarios">
|
||||
<thead class="table-dark">
|
||||
<tr>
|
||||
<th>#</th>
|
||||
<th>ID Usuario</th>
|
||||
<th>Acción</th>
|
||||
<th>Descripción</th>
|
||||
<th>Fecha</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<?php foreach ($registros as $r): ?>
|
||||
<tr>
|
||||
<td><?= $r['id_bitacora'] ?></td>
|
||||
<td><?= $r['usuario_id'] ?></td>
|
||||
<td><strong><?= htmlspecialchars($r['accion']) ?></strong></td>
|
||||
<td><?= nl2br(htmlspecialchars($r['descripcion'])) ?></td>
|
||||
<td><?= $r['fecha'] instanceof DateTime ? $r['fecha']->format('Y-m-d H:i') : htmlspecialchars($r['fecha']) ?></td>
|
||||
</tr>
|
||||
<?php endforeach; ?>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
$(document).ready(function () {
|
||||
$('#tabla-bitacora-usuarios').DataTable({
|
||||
order: [],
|
||||
language: {
|
||||
url: 'https://cdn.datatables.net/plug-ins/1.13.4/i18n/es-ES.json'
|
||||
}
|
||||
});
|
||||
});
|
||||
</script>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -4,7 +4,7 @@
|
||||
<html lang="es">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>🛠️ Cambios de Usuario</title>
|
||||
<title>👥 Registro de Usuarios</title>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
|
||||
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
|
||||
@@ -14,7 +14,7 @@
|
||||
<style>
|
||||
body { font-family: 'Segoe UI', sans-serif; background-color: #f4f6f9; }
|
||||
.sidebar { width: 220px; height: 100vh; background-color: #343a40; position: fixed; top: 0; left: 0; padding-top: 56px; z-index: 1040; }
|
||||
.sidebar .nav-link { font-weight: normal; color: white; transition: all 0.3s ease; }
|
||||
.sidebar .nav-link { font-weight: bold; color: white; transition: all 0.3s ease; }
|
||||
.sidebar .nav-link:hover,
|
||||
.sidebar .nav-link.active { background-color: #495057; color: #fff; }
|
||||
.content { margin-top: 56px; padding: 40px 20px; position: relative; z-index: 1; background-color: #f4f6f9; transition: margin-left 0.3s ease; }
|
||||
@@ -29,34 +29,44 @@
|
||||
.sidebar .nav-link.active { background-color: #e9ecef; color: #212529; }
|
||||
}
|
||||
.card { border-radius: 12px; }
|
||||
.table thead th { background: #343a40; color: #fff; }
|
||||
table.dataTable thead th { background: #343a40; color: #fff; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<div class="content">
|
||||
<h4 class="mb-4">🛠️ Cambios de Usuario</h4>
|
||||
<h4 class="mb-4">👥 Registro de Usuarios</h4>
|
||||
|
||||
<div class="card p-3 shadow-sm">
|
||||
<div class="table-responsive">
|
||||
<table class="table table-striped align-middle" id="tabla-bitacora-usuarios">
|
||||
<table class="table table-striped" id="tabla-registros-usuarios">
|
||||
<thead class="table-dark">
|
||||
<tr>
|
||||
<th>#</th>
|
||||
<th>ID Usuario</th>
|
||||
<th>Acción</th>
|
||||
<th>Descripción</th>
|
||||
<th>ID</th>
|
||||
<th>Nombre</th>
|
||||
<th>Correo</th>
|
||||
<th>Tipo</th>
|
||||
<th>Fecha</th>
|
||||
<th>Estatus</th>
|
||||
<th>Aprobado por</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<?php foreach ($registros as $r): ?>
|
||||
<tr>
|
||||
<td><?= $r['id_bitacora'] ?></td>
|
||||
<td><?= $r['usuario_id'] ?></td>
|
||||
<td><strong><?= htmlspecialchars($r['accion']) ?></strong></td>
|
||||
<td><?= nl2br(htmlspecialchars($r['descripcion'])) ?></td>
|
||||
<td><?= $r['fecha'] instanceof DateTime ? $r['fecha']->format('Y-m-d H:i') : htmlspecialchars($r['fecha']) ?></td>
|
||||
<?php foreach ($usuarios as $u): ?>
|
||||
<tr>
|
||||
<td><?= htmlspecialchars($u['id_usuario'] ?? '') ?></td>
|
||||
<td><?= htmlspecialchars(decrypt($u['nombre'] ?? '')) ?></td>
|
||||
<td><?= htmlspecialchars(decrypt($u['email'] ?? '')) ?></td>
|
||||
<td><?= htmlspecialchars($u['tipo_usuario'] ?? '') ?></td>
|
||||
<td><?= htmlspecialchars($u['creado_en'] ? $u['creado_en']->format('Y-m-d H:i:s') : '') ?></td>
|
||||
<td>
|
||||
<?php if (($u['activo'] ?? 0) == 1): ?>
|
||||
<span class="text-success fw-bold">Activo</span>
|
||||
<?php else: ?>
|
||||
<span class="text-danger fw-bold">Inactivo</span>
|
||||
<?php endif; ?>
|
||||
</td>
|
||||
<td><?= htmlspecialchars(decrypt($u['nombre_creador'] ?? '')) ?></td>
|
||||
</tr>
|
||||
<?php endforeach; ?>
|
||||
</tbody>
|
||||
@@ -67,7 +77,7 @@
|
||||
|
||||
<script>
|
||||
$(document).ready(function () {
|
||||
$('#tabla-bitacora-usuarios').DataTable({
|
||||
$('#tabla-registros-usuarios').DataTable({
|
||||
order: [],
|
||||
language: {
|
||||
url: 'https://cdn.datatables.net/plug-ins/1.13.4/i18n/es-ES.json'
|
||||
@@ -75,6 +85,6 @@
|
||||
});
|
||||
});
|
||||
</script>
|
||||
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -26,6 +26,9 @@
|
||||
.sidebar .nav-link.active { background-color: #e9ecef; color: #212529; }
|
||||
}
|
||||
.card { border-radius: 12px; }
|
||||
.btn-indigo { background-color: #6610f2; color: white; }
|
||||
.btn-indigo:hover { background-color: #520dc2; color: white; }
|
||||
.text-indigo { color: #520dc2; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
@@ -47,20 +50,30 @@
|
||||
</div>
|
||||
<div class="col-md-4">
|
||||
<div class="card shadow-sm p-3">
|
||||
<h5 class="text-success">Registro de usuarios</h5>
|
||||
<h5 class="text-success">Cambios de usuarios</h5>
|
||||
<p>Ver cambios realizados por los usuarios.</p>
|
||||
<a href="/IMPORTADORES/bitacoras/cambios"
|
||||
class="btn btn-success btn-sm mt-2 <?= $_SERVER['REQUEST_URI'] === '/IMPORTADORES/bitacoras/cambios' ? 'active' : '' ?>">
|
||||
Ver cambios
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-4">
|
||||
<div class="card shadow-sm p-3">
|
||||
<h5 class="text-info">Registro de usuarios</h5>
|
||||
<p>Ver registros de los usuarios.</p>
|
||||
<a href="/IMPORTADORES/bitacoras/usuarios"
|
||||
class="btn btn-success btn-sm mt-2 <?= $_SERVER['REQUEST_URI'] === '/IMPORTADORES/bitacoras/usuarios' ? 'active' : '' ?>">
|
||||
class="btn btn-info btn-sm mt-2 <?= $_SERVER['REQUEST_URI'] === '/IMPORTADORES/bitacoras/usuarios' ? 'active' : '' ?>">
|
||||
Ver registro de usuarios
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-4">
|
||||
<div class="card shadow-sm p-3">
|
||||
<h5 class="text-info">Registro de agencias</h5>
|
||||
<h5 class="text-indigo">Registro de agencias</h5>
|
||||
<p>Ver registros de las agencias.</p>
|
||||
<a href="/IMPORTADORES/bitacoras/agencias"
|
||||
class="btn btn-info btn-sm mt-2 <?= $_SERVER['REQUEST_URI'] === '/IMPORTADORES/bitacoras/agencias' ? 'active' : '' ?>">
|
||||
class="btn btn-indigo btn-sm mt-2 <?= $_SERVER['REQUEST_URI'] === '/IMPORTADORES/bitacoras/agencias' ? 'active' : '' ?>">
|
||||
Ver registro de agencias
|
||||
</a>
|
||||
</div>
|
||||
|
||||
@@ -16,15 +16,15 @@
|
||||
.sidebar .nav-link.active { background-color: #495057; color: #fff; }
|
||||
.content { margin-top: 56px; padding: 40px 20px; position: relative; z-index: 1; background-color: #f4f6f9; transition: margin-left 0.3s ease; }
|
||||
.navbar { position: fixed; top: 0; width: 100%; z-index: 1050; }
|
||||
.btn-indigo { background-color: #6610f2; color: white;}
|
||||
.btn-indigo:hover { background-color: #520dc2; color: white;}
|
||||
.text-indigo { color: #520dc2;}
|
||||
.btn-orange { background-color: orangeRed; color: white;}
|
||||
.btn-orange:hover { background-color: #ff3600; color: white;}
|
||||
.text-orange { color: orangeRed;}
|
||||
.btn-indigo { background-color: #6610f2; color: white; }
|
||||
.btn-indigo:hover { background-color: #520dc2; color: white; }
|
||||
.text-indigo { color: #520dc2; }
|
||||
.btn-orange { background-color: orangeRed; color: white; }
|
||||
.btn-orange:hover { background-color: #ff3600; color: white; }
|
||||
.text-orange { color: orangeRed; }
|
||||
.btn-teal { background-color: #20c997; color: white; }
|
||||
.btn-teal:hover { background-color: #4dd4ac; color: black; }
|
||||
.text-teal { color: #20c997; }
|
||||
.text-teal { color: #20c997; }
|
||||
/* A partir de dispositivos medianos (>=768px), deja espacio lateral */
|
||||
@media (min-width: 768px) { .content { margin-left: 250px; /* Ancho del sidebar */ } }
|
||||
/* En móviles, sin margen lateral */
|
||||
|
||||
@@ -107,7 +107,7 @@ if (!isset($_SESSION['recuperacion_autorizada'])) {
|
||||
|
||||
<script>
|
||||
document.getElementById('formNueva').addEventListener('submit', function(e) {
|
||||
const pass = this.password.value;
|
||||
const pass = this.password.value;
|
||||
const confirm = this.confirmar.value;
|
||||
|
||||
if (pass !== confirm) {
|
||||
|
||||
@@ -173,16 +173,16 @@ if (!isset($_SESSION['email_recuperacion'])) {
|
||||
|
||||
<script>
|
||||
document.addEventListener('DOMContentLoaded', function () {
|
||||
const form = document.getElementById('formCodigo');
|
||||
const mensaje = document.getElementById('mensaje');
|
||||
const inputCodigo = document.getElementById('codigo');
|
||||
const form = document.getElementById('formCodigo');
|
||||
const mensaje = document.getElementById('mensaje');
|
||||
const inputCodigo = document.getElementById('codigo');
|
||||
const btnVerificar = document.getElementById('btnVerificar');
|
||||
const btnReenviar = document.getElementById('btnReenviarRespaldo');
|
||||
const clearBtn = document.getElementById('clearCode');
|
||||
const btnReenviar = document.getElementById('btnReenviarRespaldo');
|
||||
const clearBtn = document.getElementById('clearCode');
|
||||
const intentosInfo = document.getElementById('intentosInfo');
|
||||
|
||||
let intentosRealizados = 0;
|
||||
const maxIntentos = 5;
|
||||
const maxIntentos = 3; // ⬅️ Cambiado de 5 a 3 para el controlador interno
|
||||
|
||||
// Auto-focus en el input al cargar
|
||||
inputCodigo.focus();
|
||||
@@ -220,14 +220,6 @@ if (!isset($_SESSION['email_recuperacion'])) {
|
||||
}
|
||||
});
|
||||
|
||||
// Auto-envío cuando se completen 6 dígitos (opcional)
|
||||
inputCodigo.addEventListener('input', function() {
|
||||
if (this.value.length === 6) {
|
||||
// Opcional: enviar automáticamente después de un breve delay
|
||||
// setTimeout(() => form.dispatchEvent(new Event('submit')), 500);
|
||||
}
|
||||
});
|
||||
|
||||
// Manejo del formulario
|
||||
form.addEventListener('submit', function(e) {
|
||||
e.preventDefault();
|
||||
@@ -235,7 +227,7 @@ if (!isset($_SESSION['email_recuperacion'])) {
|
||||
const codigo = inputCodigo.value.trim();
|
||||
if (!validarCodigo(codigo)) return;
|
||||
|
||||
enviarCodigo(codigo);
|
||||
enviarCodigoInterno(codigo);
|
||||
});
|
||||
|
||||
// Validación del código
|
||||
@@ -260,8 +252,8 @@ if (!isset($_SESSION['email_recuperacion'])) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Enviar código para verificación
|
||||
function enviarCodigo(codigo) {
|
||||
// ⬅️ NUEVA FUNCIÓN: Enviar código para verificación INTERNA
|
||||
function enviarCodigoInterno(codigo) {
|
||||
// Mostrar estado de carga
|
||||
btnVerificar.disabled = true;
|
||||
btnVerificar.classList.add('loading');
|
||||
@@ -270,34 +262,43 @@ if (!isset($_SESSION['email_recuperacion'])) {
|
||||
const formData = new FormData();
|
||||
formData.append('codigo', codigo);
|
||||
|
||||
fetch('/IMPORTADORES/login/verificarCodigo', {
|
||||
fetch('/IMPORTADORES/reset/verificarCodigoInterno', {
|
||||
method: 'POST',
|
||||
body: formData,
|
||||
credentials: 'same-origin'
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
if (data.blocked) {
|
||||
mostrarError(data.message); // <-- función personalizada con un div bonito
|
||||
setTimeout(() => {
|
||||
window.location.href = data.redirect;
|
||||
}, 4000);
|
||||
.then(response => {
|
||||
// ⬅️ IMPORTANTE: Verificar si la respuesta es un redirect (302/200 HTML)
|
||||
if (response.ok && response.headers.get('content-type')?.includes('text/html')) {
|
||||
// Si el servidor devolvió HTML, significa que hubo un redirect exitoso
|
||||
mostrarExito("✅ Código verificado correctamente. Redirigiendo...");
|
||||
inputCodigo.classList.add('success');
|
||||
inputCodigo.disabled = true;
|
||||
|
||||
setTimeout(() => {
|
||||
window.location.href = '/IMPORTADORES/reset/cambiarPasswordInternoView';
|
||||
}, 1500);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
// Si no es HTML, intentar parsear como JSON (para errores)
|
||||
return response.json();
|
||||
})
|
||||
.then(data => {
|
||||
if (!data) return; // Ya fue manejado arriba como éxito
|
||||
|
||||
// Manejar respuestas de error JSON
|
||||
if (data.success) {
|
||||
// Código correcto
|
||||
mostrarExito(data.message);
|
||||
inputCodigo.classList.add('success');
|
||||
inputCodigo.disabled = true;
|
||||
|
||||
// Redirigir al formulario de cambio de contraseña
|
||||
setTimeout(() => {
|
||||
window.location.href = '/IMPORTADORES/login/cambiarPasswordVista';
|
||||
window.location.href = '/IMPORTADORES/reset/cambiarPasswordInternoView';
|
||||
}, 1500);
|
||||
|
||||
} else {
|
||||
// Código incorrecto
|
||||
manejarCodigoIncorrecto(data);
|
||||
manejarCodigoIncorrectoInterno(data);
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
@@ -314,57 +315,27 @@ if (!isset($_SESSION['email_recuperacion'])) {
|
||||
});
|
||||
}
|
||||
|
||||
// Mostrar error de cuenta bloqueada
|
||||
function mostrarError(mensaje) {
|
||||
const mensajeDiv = document.getElementById('mensaje');
|
||||
mensajeDiv.innerHTML = `
|
||||
<div class="text-danger fade-in">
|
||||
<i class="fas fa-exclamation-triangle me-2"></i> ${mensaje}
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
// Manejar código incorrecto
|
||||
function manejarCodigoIncorrecto(data) {
|
||||
// ⬅️ NUEVA FUNCIÓN: Manejar errores específicos del controlador interno
|
||||
function manejarCodigoIncorrectoInterno(data) {
|
||||
intentosRealizados++;
|
||||
|
||||
mostrarError(data.message);
|
||||
mostrarError(data.message || "❌ Código incorrecto.");
|
||||
inputCodigo.classList.add('error');
|
||||
|
||||
// Limpiar input y enfocar para nuevo intento
|
||||
limpiarYEnfocarInput();
|
||||
|
||||
// Actualizar contador de intentos
|
||||
actualizarContadorIntentos();
|
||||
actualizarContadorIntentosInterno();
|
||||
|
||||
// Si se bloqueó el código
|
||||
if (data.blocked) {
|
||||
bloquearFormulario();
|
||||
// Si se excedieron los intentos (3 para interno)
|
||||
if (intentosRealizados >= maxIntentos) {
|
||||
bloquearFormularioInterno();
|
||||
}
|
||||
}
|
||||
|
||||
// Limpiar input y enfocar
|
||||
function limpiarYEnfocarInput() {
|
||||
setTimeout(() => {
|
||||
inputCodigo.value = '';
|
||||
inputCodigo.classList.remove('error');
|
||||
inputCodigo.focus();
|
||||
clearBtn.style.display = 'none';
|
||||
}, 1500); // Esperar 1.5 segundos antes de limpiar
|
||||
}
|
||||
|
||||
// Actualizar contador visual
|
||||
function actualizarContadorVisual() {
|
||||
const longitud = inputCodigo.value.length;
|
||||
if (longitud > 0) {
|
||||
inputCodigo.setAttribute('placeholder', '0'.repeat(6 - longitud) + inputCodigo.value);
|
||||
} else {
|
||||
inputCodigo.setAttribute('placeholder', '000000');
|
||||
}
|
||||
}
|
||||
|
||||
// Actualizar contador de intentos
|
||||
function actualizarContadorIntentos() {
|
||||
// ⬅️ MODIFICADA: Actualizar contador de intentos para interno
|
||||
function actualizarContadorIntentosInterno() {
|
||||
if (intentosRealizados > 0) {
|
||||
const restantes = maxIntentos - intentosRealizados;
|
||||
intentosInfo.innerHTML = `
|
||||
@@ -375,21 +346,43 @@ if (!isset($_SESSION['email_recuperacion'])) {
|
||||
}
|
||||
}
|
||||
|
||||
// Bloquear formulario cuando se exceden intentos
|
||||
function bloquearFormulario() {
|
||||
// ⬅️ MODIFICADA: Bloquear formulario para interno
|
||||
function bloquearFormularioInterno() {
|
||||
inputCodigo.disabled = true;
|
||||
btnVerificar.disabled = true;
|
||||
btnReenviar.disabled = true;
|
||||
if (btnReenviar) btnReenviar.disabled = true;
|
||||
|
||||
intentosInfo.innerHTML = `
|
||||
<i class="fas fa-ban text-danger me-1"></i>
|
||||
<span class="text-danger">Código bloqueado por seguridad</span>
|
||||
<span class="text-danger">Demasiados intentos fallidos</span>
|
||||
`;
|
||||
|
||||
// Redirigir a solicitar nuevo código después de 5 segundos
|
||||
mostrarError("❌ Demasiados intentos fallidos. Redirigiendo...");
|
||||
|
||||
// Redirigir a la página de seguridad después de 3 segundos
|
||||
setTimeout(() => {
|
||||
window.location.href = '/IMPORTADORES/login/recuperar';
|
||||
}, 5000);
|
||||
window.location.href = '/IMPORTADORES/seguridad/index';
|
||||
}, 3000);
|
||||
}
|
||||
|
||||
// Limpiar input y enfocar
|
||||
function limpiarYEnfocarInput() {
|
||||
setTimeout(() => {
|
||||
inputCodigo.value = '';
|
||||
inputCodigo.classList.remove('error');
|
||||
inputCodigo.focus();
|
||||
clearBtn.style.display = 'none';
|
||||
}, 1500);
|
||||
}
|
||||
|
||||
// Actualizar contador visual
|
||||
function actualizarContadorVisual() {
|
||||
const longitud = inputCodigo.value.length;
|
||||
if (longitud > 0) {
|
||||
inputCodigo.setAttribute('placeholder', '0'.repeat(6 - longitud) + inputCodigo.value);
|
||||
} else {
|
||||
inputCodigo.setAttribute('placeholder', '000000');
|
||||
}
|
||||
}
|
||||
|
||||
// Funciones de utilidad para mensajes
|
||||
@@ -414,40 +407,39 @@ if (!isset($_SESSION['email_recuperacion'])) {
|
||||
mensaje.innerHTML = '';
|
||||
}
|
||||
|
||||
// Manejo del botón de reenvío
|
||||
btnReenviar.addEventListener("click", function() {
|
||||
const btnOriginalText = this.innerHTML;
|
||||
|
||||
// Deshabilitar botón temporalmente
|
||||
this.disabled = true;
|
||||
this.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>Enviando...';
|
||||
|
||||
fetch("/IMPORTADORES/login/reenviarCodigo", {
|
||||
method: "POST",
|
||||
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
|
||||
body: "accion=reenviarCodigo"
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
mostrarInfo(data.message);
|
||||
// Manejo del botón de reenvío (si existe)
|
||||
if (btnReenviar) {
|
||||
btnReenviar.addEventListener("click", function() {
|
||||
const btnOriginalText = this.innerHTML;
|
||||
|
||||
// Habilitar botón después de 30 segundos
|
||||
setTimeout(() => {
|
||||
this.disabled = true;
|
||||
this.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>Enviando...';
|
||||
|
||||
fetch("/IMPORTADORES/reset/reenviarCodigoInterno", {
|
||||
method: "POST",
|
||||
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
|
||||
body: "accion=reenviarCodigo"
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
mostrarInfo(data.message);
|
||||
|
||||
setTimeout(() => {
|
||||
this.disabled = false;
|
||||
this.innerHTML = btnOriginalText;
|
||||
}, 30000);
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Error:', error);
|
||||
mostrarError("❌ Error al reenviar código.");
|
||||
|
||||
this.disabled = false;
|
||||
this.innerHTML = btnOriginalText;
|
||||
}, 30000);
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Error:', error);
|
||||
mostrarError("❌ Error al reenviar código.");
|
||||
|
||||
// Restaurar botón en caso de error
|
||||
this.disabled = false;
|
||||
this.innerHTML = btnOriginalText;
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Manejar tecla Enter en cualquier parte del formulario
|
||||
// Manejar tecla Enter
|
||||
document.addEventListener('keypress', function(e) {
|
||||
if (e.key === 'Enter' && !btnVerificar.disabled) {
|
||||
form.dispatchEvent(new Event('submit'));
|
||||
|
||||
@@ -20,6 +20,7 @@ $permisos = [
|
||||
'seguridad' => true,
|
||||
'bitacoras' => [
|
||||
'registro_accesos' => true,
|
||||
'registro_cambios' => true,
|
||||
'registro_usuarios' => true,
|
||||
'registro_agencias' => true,
|
||||
'mi_actividad' => true
|
||||
@@ -85,7 +86,8 @@ $cantidadBitacoras = contarBitacorasDisponibles($permisosBitacoras);
|
||||
function obtenerTextoPermiso($permiso, $tipoUsuario) {
|
||||
$textos = [
|
||||
'registro_accesos' => ($tipoUsuario === 'super_admin') ? 'Registro de accesos' : null,
|
||||
'registro_usuarios' => ($tipoUsuario === 'super_admin') ? 'Cambios de usuarios' : null,
|
||||
'registro_cambios' => ($tipoUsuario === 'super_admin') ? 'Cambios de usuarios' : null,
|
||||
'registro_usuarios' => ($tipoUsuario === 'super_admin') ? 'Registro de usuarios' : null,
|
||||
'registro_agencias' => ($tipoUsuario === 'super_admin') ? 'Registro de agencias' : null,
|
||||
'acceso_usuarios_agencia' => ($tipoUsuario === 'admin_agencia' || $tipoUsuario === 'agente_aduanal') ? 'Registro de accesos' : null,
|
||||
'registro_vinculaciones' => ($tipoUsuario === 'admin_agencia' || $tipoUsuario === 'agente_aduanal') ? 'Vinculaciones (Agencia)' : null,
|
||||
@@ -100,6 +102,7 @@ function obtenerTextoPermiso($permiso, $tipoUsuario) {
|
||||
function obtenerIconoPermiso($permiso) {
|
||||
$iconos = [
|
||||
'registro_accesos' => '🌐',
|
||||
'registro_cambios' => '🔄',
|
||||
'registro_usuarios' => '👥',
|
||||
'registro_agencias' => '🏪',
|
||||
'acceso_usuarios_agencia' => '👥',
|
||||
@@ -115,12 +118,13 @@ function obtenerIconoPermiso($permiso) {
|
||||
function obtenerUrlPermiso($permiso) {
|
||||
$urls = [
|
||||
'registro_accesos' => '/IMPORTADORES/bitacoras/sistema', // ✅
|
||||
'registro_usuarios' => '/IMPORTADORES/bitacoras/usuarios', // ✅
|
||||
'registro_cambios' => '/IMPORTADORES/bitacoras/cambios', // ✅
|
||||
'registro_usuarios' => '/IMPORTADORES/bitacoras/usuarios', //
|
||||
'registro_agencias' => '/IMPORTADORES/bitacoras/agencias', // ✅
|
||||
'acceso_usuarios_agencia' => '/IMPORTADORES/bitacoras/sistemaAgencia', // ✅
|
||||
'registro_vinculaciones' => '/IMPORTADORES/bitacoras/vinculaciones', // ✅
|
||||
'mi_actividad' => '/IMPORTADORES/bitacoras/miAcceso', // ✅
|
||||
'vinculaciones_usuario' => '/IMPORTADORES/bitacoras/vinculacionesUsuario' //
|
||||
'vinculaciones_usuario' => '/IMPORTADORES/bitacoras/vinculacionesUsuario' // ✅
|
||||
];
|
||||
|
||||
return $urls[$permiso] ?? '/IMPORTADORES/bitacoras/index';
|
||||
@@ -158,19 +162,19 @@ function obtenerUrlPermiso($permiso) {
|
||||
<span class="user-badge bg-info text-dark ms-2"><?= strtoupper(str_replace('_', ' ', $tipoUsuario)) ?></span>
|
||||
</span>
|
||||
<div class="d-flex ms-auto">
|
||||
<?php
|
||||
// Definir la URL de regreso según el tipo de usuario
|
||||
$urlRegreso = match($tipoUsuario) {
|
||||
'super_admin' => '/IMPORTADORES/administrador/dashboard',
|
||||
'admin_agencia' => '/IMPORTADORES/agencias/dashboard',
|
||||
'agente_aduanal' => '/IMPORTADORES/agentes/dashboard',
|
||||
'importador' => '/IMPORTADORES/importadores/dashboard',
|
||||
default => '/IMPORTADORES/importadores/dashboard'
|
||||
};
|
||||
?>
|
||||
<a href="<?= $urlRegreso ?>" class="btn btn-outline-light btn-sm" style="margin: 0 0 0 25px;">
|
||||
← Panel Principal
|
||||
</a>
|
||||
<?php
|
||||
// Definir la URL de regreso según el tipo de usuario
|
||||
$urlRegreso = match($tipoUsuario) {
|
||||
'super_admin' => '/IMPORTADORES/administrador/dashboard',
|
||||
'admin_agencia' => '/IMPORTADORES/agencias/dashboard',
|
||||
'agente_aduanal' => '/IMPORTADORES/agentes/dashboard',
|
||||
'importador' => '/IMPORTADORES/importadores/dashboard',
|
||||
default => '/IMPORTADORES/importadores/dashboard'
|
||||
};
|
||||
?>
|
||||
<a href="<?= $urlRegreso ?>" class="btn btn-outline-light btn-sm" style="margin: 0 0 0 25px;">
|
||||
← Panel Principal
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
@@ -191,6 +195,8 @@ function obtenerUrlPermiso($permiso) {
|
||||
$esVistaPreferencias = str_contains($_SERVER['REQUEST_URI'], '/preferencias');
|
||||
// Detecta si estamos en alguna parte de automatizaciones
|
||||
$esVistaAutomatizaciones = str_contains($_SERVER['REQUEST_URI'], '/automatizaciones');
|
||||
// Detecta si estamos en alguna parte del reset
|
||||
$esVistaReset = str_contains($_SERVER['REQUEST_URI'], '/reset');
|
||||
?>
|
||||
|
||||
<!-- INFORMACIÓN GENERAL -->
|
||||
@@ -209,7 +215,7 @@ function obtenerUrlPermiso($permiso) {
|
||||
class="nav-link px-3 py-2 <?= str_contains($_SERVER['REQUEST_URI'], '/automatizaciones/index') ? 'active' : '' ?>">
|
||||
⚙️ Automatizaciones
|
||||
</a>
|
||||
<?php elseif ($esConfiguracion || $esVistaSeguridad || $esVistaPreferencias || $esVistaBitacoras): ?>
|
||||
<?php elseif ($esConfiguracion || $esVistaSeguridad || $esVistaPreferencias || $esVistaBitacoras || $esVistaReset): ?>
|
||||
<a href="/IMPORTADORES/automatizaciones/index"
|
||||
class="nav-link px-3 py-2 <?= str_contains($_SERVER['REQUEST_URI'], '/automatizaciones/index') ? 'active' : '' ?>">
|
||||
⚙️ Automatizaciones
|
||||
@@ -237,7 +243,7 @@ function obtenerUrlPermiso($permiso) {
|
||||
</a>
|
||||
</nav>
|
||||
</div>
|
||||
<?php elseif ($esConfiguracion || $esVistaAutomatizaciones || $esVistaSeguridad || $esVistaBitacoras): ?>
|
||||
<?php elseif ($esConfiguracion || $esVistaAutomatizaciones || $esVistaSeguridad || $esVistaBitacoras || $esVistaReset): ?>
|
||||
<a href="/IMPORTADORES/preferencias/index"
|
||||
class="nav-link px-3 py-2 d-flex justify-content-between align-items-center">
|
||||
✅ Preferencias
|
||||
@@ -266,7 +272,7 @@ function obtenerUrlPermiso($permiso) {
|
||||
</a>
|
||||
</nav>
|
||||
</div>
|
||||
<?php elseif ($esConfiguracion || $esVistaAutomatizaciones || $esVistaPreferencias || $esVistaBitacoras): ?>
|
||||
<?php elseif ($esConfiguracion || $esVistaAutomatizaciones || $esVistaPreferencias || $esVistaBitacoras || $esVistaReset): ?>
|
||||
<a href="/IMPORTADORES/seguridad/index"
|
||||
class="nav-link px-3 py-2 d-flex justify-content-between align-items-center">
|
||||
👮 Seguridad
|
||||
@@ -353,7 +359,7 @@ function obtenerUrlPermiso($permiso) {
|
||||
class="nav-link px-3 py-2 <?= str_contains($_SERVER['REQUEST_URI'], '/automatizaciones/index') ? 'active' : '' ?>">
|
||||
⚙️ Automatizaciones
|
||||
</a>
|
||||
<?php elseif ($esConfiguracion || $esVistaSeguridad || $esVistaPreferencias || $esVistaBitacoras): ?>
|
||||
<?php elseif ($esConfiguracion || $esVistaSeguridad || $esVistaPreferencias || $esVistaBitacoras || $esVistaReset): ?>
|
||||
<a href="/IMPORTADORES/automatizaciones/index"
|
||||
class="nav-link px-3 py-2 <?= str_contains($_SERVER['REQUEST_URI'], '/automatizaciones/index') ? 'active' : '' ?>">
|
||||
⚙️ Automatizaciones
|
||||
@@ -381,7 +387,7 @@ function obtenerUrlPermiso($permiso) {
|
||||
</a>
|
||||
</nav>
|
||||
</div>
|
||||
<?php elseif ($esConfiguracion || $esVistaAutomatizaciones || $esVistaSeguridad || $esVistaBitacoras): ?>
|
||||
<?php elseif ($esConfiguracion || $esVistaAutomatizaciones || $esVistaSeguridad || $esVistaBitacoras || $esVistaReset): ?>
|
||||
<a href="/IMPORTADORES/preferencias/index"
|
||||
class="nav-link px-3 py-2 d-flex justify-content-between align-items-center">
|
||||
✅ Preferencias
|
||||
@@ -410,7 +416,7 @@ function obtenerUrlPermiso($permiso) {
|
||||
</a>
|
||||
</nav>
|
||||
</div>
|
||||
<?php elseif ($esConfiguracion || $esVistaAutomatizaciones || $esVistaPreferencias || $esVistaBitacoras): ?>
|
||||
<?php elseif ($esConfiguracion || $esVistaAutomatizaciones || $esVistaPreferencias || $esVistaBitacoras || $esVistaReset): ?>
|
||||
<a href="/IMPORTADORES/seguridad/index"
|
||||
class="nav-link px-3 py-2 d-flex justify-content-between align-items-center">
|
||||
👮 Seguridad
|
||||
|
||||
@@ -47,7 +47,7 @@
|
||||
</a>
|
||||
|
||||
<!-- VINCULACIONES -->
|
||||
<a class="nav-link px-3 py-2 d-flex justify-content-between align-items-center
|
||||
<a class="nav-link px-3 py-2 d-flex justify-content-between align-items-center
|
||||
<?= str_contains($_SERVER['REQUEST_URI'], '/IMPORTADORES/vinculaciones') ? 'active' : '' ?>"
|
||||
data-bs-toggle="collapse" href="#submenuVinculaciones" role="button" aria-expanded="false">
|
||||
🔗 Vinculación
|
||||
@@ -66,7 +66,6 @@
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
|
||||
<!-- TRANSPORTISTAS -->
|
||||
<a class="nav-link px-3 py-2 d-flex justify-content-between align-items-center
|
||||
<?= str_contains($_SERVER['REQUEST_URI'], '/IMPORTADORES/transportistas') ? 'active' : '' ?>"
|
||||
@@ -244,7 +243,7 @@
|
||||
</a>
|
||||
|
||||
<!-- VINCULACIONES -->
|
||||
<a class="nav-link px-3 py-2 d-flex justify-content-between align-items-center
|
||||
<a class="nav-link px-3 py-2 d-flex justify-content-between align-items-center
|
||||
<?= str_contains($_SERVER['REQUEST_URI'], '/IMPORTADORES/vinculaciones') ? 'active' : '' ?>"
|
||||
data-bs-toggle="collapse" href="#submenuVinculaciones" role="button" aria-expanded="false">
|
||||
🔗 Vinculación
|
||||
@@ -262,7 +261,6 @@
|
||||
</a>
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
|
||||
<!-- TRANSPORTISTAS -->
|
||||
<a class="nav-link px-3 py-2 d-flex justify-content-between align-items-center
|
||||
|
||||
427
views/reset/change_password.php
Normal file
427
views/reset/change_password.php
Normal file
@@ -0,0 +1,427 @@
|
||||
<?php
|
||||
include __DIR__ . '/../partials/sidebar_configuracion.php';
|
||||
|
||||
$dos_factores_estado = obtenerEstadoDosFactores();
|
||||
?>
|
||||
<!DOCTYPE html>
|
||||
<html lang="es">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>👮 Opciones de Seguridad</title>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
|
||||
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.2/sweetalert.min.js"></script>
|
||||
<style>
|
||||
body { font-family: 'Segoe UI', sans-serif; background-color: #f4f6f9; }
|
||||
.sidebar { width: 220px; height: 100vh; background-color: #343a40; position: fixed; top: 0; left: 0; padding-top: 56px; z-index: 1040; }
|
||||
.sidebar .nav-link { font-weight: bold; color: white; transition: all 0.3s ease; }
|
||||
.sidebar .nav-link:hover,
|
||||
.sidebar .nav-link.active { background-color: #495057; color: #fff; }
|
||||
.content { margin-top: 56px; padding: 40px 20px; position: relative; z-index: 1; background-color: #f4f6f9; transition: margin-left 0.3s ease; }
|
||||
.navbar { position: fixed; top: 0; width: 100%; z-index: 1050; }
|
||||
/* Contenedor de fondo semitransparente para las vistas */
|
||||
.overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.5); z-index: 9999; }
|
||||
.login-container { position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); max-width: 420px; width: 90%;
|
||||
background: white; padding: 40px; border-radius: 12px; box-shadow: 0 10px 25px rgba(0, 0, 0, 0.08); z-index: 10000; margin: 0; }
|
||||
.form-control { border-radius: 6px; transition: all 0.3s ease; }
|
||||
/* A partir de dispositivos medianos (>=768px), deja espacio lateral */
|
||||
@media (min-width: 768px) { .content { margin-left: 250px; /* Ancho del sidebar */ } }
|
||||
/* En móviles, sin margen lateral */
|
||||
@media (max-width: 767.98px) {
|
||||
.content { margin-left: 0; }
|
||||
.sidebar .nav-link { font-weight: normal; color: #343a40; background-color: transparent; }
|
||||
.sidebar .nav-link:hover,
|
||||
.sidebar .nav-link.active { background-color: #e9ecef; color: #212529; }
|
||||
.login-container { width: 95%; padding: 30PX 20px; }
|
||||
}
|
||||
.card { border-radius: 12px; }
|
||||
.btn i { font-family: "Font Awesome 6 Free", sans-serif; margin-right: 0.5rem; }
|
||||
.btn { font-family: 'Segoe UI', sans-serif; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<!-- Overlay (fondo semitransparente) que cubre la pantalla -->
|
||||
<div class="overlay"></div>
|
||||
|
||||
<!-- Formulario de cambio de contraseña -->
|
||||
<div class="login-container">
|
||||
<h4 class="mb-4 text-center" style="color:<?= $color1 ?>">Cambiar contraseña</h4>
|
||||
<form id="formCambiarPassword" action="/IMPORTADORES/reset/cambiarPasswordInterno" method="POST">
|
||||
<input type="hidden" name="username" value="<?= $_SESSION['usuario_email'] ?? '' ?>">
|
||||
<div class="mb-3">
|
||||
<label class="form-label">Contraseña actual:</label>
|
||||
<input type="password" name="password_actual" required id="password_actual" class="form-control" autocomplete="current-password">
|
||||
</div>
|
||||
|
||||
<div class="mb-3">
|
||||
<label class="form-label">Nueva contraseña:</label>
|
||||
<input type="password" name="password_nueva" required id="password_nueva" class="form-control" minlength="6" autocomplete="new-password">
|
||||
</div>
|
||||
|
||||
<div class="mb-3">
|
||||
<label class="form-label">Confirmar nueva contraseña:</label>
|
||||
<input type="password" name="confirmar_password" required id="confirmar_password" class="form-control">
|
||||
</div>
|
||||
|
||||
<button type="submit" class="btn btn-warning w-100" id="btnCambiarPassword">Actualizar contraseña</button>
|
||||
</form>
|
||||
<!-- Este contenedor es necesario para mensajes dinámicos con JS -->
|
||||
<div id="mensaje" class="mb-3"></div>
|
||||
</div>
|
||||
|
||||
<div class="content">
|
||||
<h4 class="mb-4">👮 Opciones de Seguridad</h4>
|
||||
<div class="row g-3">
|
||||
|
||||
<!-- Autenticacin de dos factores -->
|
||||
<div class="col-md-6">
|
||||
<div class="card shadow-sm p-3">
|
||||
<h4 class="mb-4 text-dark">Autenticación de dos factores</h4>
|
||||
<p>Al activar esta funcionalidad, blindas el acceso a tu cuenta, recibiras un código de acceso a tu correo electrónico para confirmar identidad.</p>
|
||||
<form method="POST" action="/IMPORTADORES/seguridad/autenticacionDosFactores">
|
||||
<div class="form-check form-switch mb-3">
|
||||
<input type="checkbox" name="dos_factores" id="dos_factores" class="form-check-input"
|
||||
<?php echo ($dos_factores_estado == 1) ? "checked" : ""; ?>>
|
||||
<label class="form-check-label" for="dos_factores">
|
||||
<?php echo ($dos_factores_estado == 1) ? "Activo" : "Inactivo"; ?>
|
||||
</label>
|
||||
</div>
|
||||
<button type="submit" class="btn btn-primary"><i class="fas fa-floppy-disk"></i>Guardar configuración</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Cambiar contraseña -->
|
||||
<div class="col-md-6">
|
||||
<div class="card shadow-sm p-3">
|
||||
<h4 class="mb-4 text-dark">Cambiar contraseña</h4>
|
||||
<p>Al actualizar tu contraseña, refuerzas la seguridad de tu cuenta. Te recomendamos usar una combinación de letras, números y símbolos para mayor seguridad.</p><br><br>
|
||||
<a href="/IMPORTADORES/reset/changePassword" class="btn btn-primary">Cambiar contraseña</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Correo adicional (extra) -->
|
||||
<div class="col-md-6">
|
||||
<div class="card shadow-sm p-3">
|
||||
<h4 class="mb-4 text-dark">Recibe notificaciones</h4>
|
||||
<p>Agrega un correo adicional para recibir notificaciones.</p>
|
||||
<?php if (!empty($correos['correo_extra'])): ?>
|
||||
<p><code><?= htmlspecialchars($correos['correo_extra']) ?></code></p>
|
||||
<!-- Formulario para eliminar -->
|
||||
<form method="POST" action="/IMPORTADORES/seguridad/eliminarCorreoExtra" id="form-eliminar-extra" class="mt-2 hide"></form>
|
||||
<form method="POST" action="/IMPORTADORES/seguridad/modificarCorreoExtra">
|
||||
<div class="mb-3">
|
||||
<input type="email" name="email-extra" class="form-control" value="" placeholder="Actualizar correo adicional" required>
|
||||
</div>
|
||||
<div class="d-flex gap-2">
|
||||
<button type="submit" class="btn btn-success">
|
||||
<i class="fas fa-edit"></i>Actualizar
|
||||
</button>
|
||||
<button type="button" class="btn btn-danger" onclick="confirmarEliminacion('extra')">
|
||||
<i class="fas fa-trash"></i> Eliminar correo
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
<?php else: ?>
|
||||
<form method="POST" action="/IMPORTADORES/seguridad/correoExtra">
|
||||
<div class="mb-3">
|
||||
<input type="email" name="email-extra" class="form-control" placeholder="Correo adicional" required>
|
||||
</div>
|
||||
<button type="submit" class="btn btn-primary"><i class="fas fa-envelope"></i>Registrar</button>
|
||||
</form>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Correo de Respaldo -->
|
||||
<div class="col-md-6">
|
||||
<div class="card shadow-sm p-3">
|
||||
<h4 class="mb-4 text-dark">Correo de respaldo</h4>
|
||||
<p>Agrega un correo de respaldo para reuperación de tu cuenta.</p>
|
||||
<?php if (!empty($correos['correo_respaldo'])): ?>
|
||||
<p><code><?= htmlspecialchars($correos['correo_respaldo']) ?></code></p>
|
||||
<!-- Formulario para eliminar -->
|
||||
<form method="POST" action="/IMPORTADORES/seguridad/eliminarCorreoRespaldo" id="form-eliminar-respaldo" class="mt-2 hide"></form>
|
||||
<form method="POST" action="/IMPORTADORES/seguridad/modificarCorreoRspaldo">
|
||||
<div class="mb-3">
|
||||
<input type="email" name="email-respaldo" class="form-control" value="" placeholder="Actualizar correo de respaldo" required>
|
||||
</div>
|
||||
<button type="submit" class="btn btn-success">
|
||||
<i class="fas fa-edit"></i>Actualizar
|
||||
</button>
|
||||
<button type="button" class="btn btn-danger" onclick="confirmarEliminacion('respaldo')">
|
||||
<i class="fas fa-trash"></i> Eliminar correo
|
||||
</button>
|
||||
</form>
|
||||
<?php else: ?>
|
||||
<form method="POST" action="/IMPORTADORES/seguridad/correoRespaldo">
|
||||
<div class="mb-3">
|
||||
<input type="email" name="email-respaldo" class="form-control" placeholder="Correo de respaldo" required>
|
||||
</div>
|
||||
<button type="submit" class="btn btn-primary"><i class="fas fa-envelope"></i>Registrar</button>
|
||||
</form>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
document.addEventListener('DOMContentLoaded', function () {
|
||||
const form = document.getElementById('formCambiarPassword');
|
||||
const mensaje = document.getElementById('mensaje');
|
||||
const btnCambiar = document.getElementById('btnCambiarPassword');
|
||||
|
||||
// Inputs de contraseña
|
||||
const inputActual = document.getElementById('password_actual');
|
||||
const inputNueva = document.getElementById('password_nueva');
|
||||
const inputConfirmar = document.getElementById('confirmar_password');
|
||||
|
||||
// Botones de mostrar/ocultar contraseña
|
||||
const toggleButtons = document.querySelectorAll('.toggle-password');
|
||||
|
||||
// Auto-focus en el primer input
|
||||
if (inputActual) inputActual.focus();
|
||||
|
||||
// Manejo de botones mostrar/ocultar contraseña
|
||||
toggleButtons.forEach(button => {
|
||||
button.addEventListener('click', function() {
|
||||
const targetId = this.getAttribute('data-target');
|
||||
const targetInput = document.getElementById(targetId);
|
||||
const icon = this.querySelector('i');
|
||||
|
||||
if (targetInput.type === 'password') {
|
||||
targetInput.type = 'text';
|
||||
icon.classList.remove('fa-eye');
|
||||
icon.classList.add('fa-eye-slash');
|
||||
} else {
|
||||
targetInput.type = 'password';
|
||||
icon.classList.remove('fa-eye-slash');
|
||||
icon.classList.add('fa-eye');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Validación en tiempo real
|
||||
inputNueva.addEventListener('input', function() {
|
||||
validarFortalezaPassword(this.value);
|
||||
validarCoincidencia();
|
||||
});
|
||||
|
||||
inputConfirmar.addEventListener('input', function() {
|
||||
validarCoincidencia();
|
||||
});
|
||||
|
||||
// Manejo del formulario
|
||||
form.addEventListener('submit', function(e) {
|
||||
e.preventDefault();
|
||||
|
||||
const passwordActual = inputActual.value.trim();
|
||||
const passwordNueva = inputNueva.value.trim();
|
||||
const confirmarPassword = inputConfirmar.value.trim();
|
||||
|
||||
if (!validarFormulario(passwordActual, passwordNueva, confirmarPassword)) {
|
||||
return;
|
||||
}
|
||||
enviarCambioPassword(passwordActual, passwordNueva, confirmarPassword);
|
||||
});
|
||||
|
||||
// Función para enviar cambio de contraseña
|
||||
function enviarCambioPassword(actual, nueva, confirmar) {
|
||||
// Mostrar estado de carga
|
||||
btnCambiar.disabled = true;
|
||||
btnCambiar.classList.add('loading');
|
||||
btnCambiar.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Cambiando contraseña...';
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append('password_actual', actual);
|
||||
formData.append('password_nueva', nueva);
|
||||
formData.append('confirmar_password', confirmar);
|
||||
|
||||
fetch('/IMPORTADORES/reset/cambiarPasswordInterno', {
|
||||
method: 'POST',
|
||||
body: formData,
|
||||
credentials: 'same-origin'
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
if (data.success) {
|
||||
// Éxito: mostrar mensaje y redirigir
|
||||
mostrarExito(data.message);
|
||||
|
||||
// Deshabilitar formulario
|
||||
deshabilitarFormulario();
|
||||
|
||||
// Redirigir después de 2 segundos
|
||||
setTimeout(() => {
|
||||
if (data.redirect) {
|
||||
window.location.href = data.redirect;
|
||||
} else {
|
||||
window.location.href = '/IMPORTADORES/login'; // Redirigir a login por defecto
|
||||
}
|
||||
}, 2000);
|
||||
} else {
|
||||
// Error: mostrar mensaje
|
||||
mostrarError(data.message);
|
||||
|
||||
// Limpiar contraseña actual por seguridad
|
||||
inputActual.value = '';
|
||||
inputActual.focus();
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Error:', error);
|
||||
mostrarError("❌ Error de conexión. Intenta nuevamente.");
|
||||
})
|
||||
.finally(() => {
|
||||
// Restaurar botón solo si no fue exitoso
|
||||
if (!btnCambiar.classList.contains('success')) {
|
||||
btnCambiar.disabled = false;
|
||||
btnCambiar.classList.remove('loading');
|
||||
btnCambiar.innerHTML = '<i class="fas fa-lock me-2"></i>Cambiar contraseña';
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Validar formulario antes de enviar
|
||||
function validarFormulario(actual, nueva, confirmar) {
|
||||
limpiarMensajes();
|
||||
|
||||
if (!actual) {
|
||||
mostrarError("❌ La contraseña actual es requerida.");
|
||||
inputActual.focus();
|
||||
return false;
|
||||
}
|
||||
if (nueva.length < 6) {
|
||||
mostrarError("❌ La nueva contraseña debe tener al menos 6 caracteres.");
|
||||
inputNueva.focus();
|
||||
return false;
|
||||
}
|
||||
if (nueva !== confirmar) {
|
||||
mostrarError("❌ Las contraseñas nuevas no coinciden.");
|
||||
inputConfirmar.focus();
|
||||
return false;
|
||||
}
|
||||
|
||||
if (actual === nueva) {
|
||||
mostrarError("❌ La nueva contraseña debe ser diferente a la actual.");
|
||||
inputNueva.focus();
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// Validar fortaleza de contraseña
|
||||
function validarFortalezaPassword(password) {
|
||||
const indicador = document.getElementById('passwordStrength');
|
||||
if (!indicador) return;
|
||||
|
||||
let fuerza = 0;
|
||||
let mensaje = '';
|
||||
let clase = '';
|
||||
|
||||
if (password.length >= 6) fuerza++;
|
||||
if (password.length >= 8) fuerza++;
|
||||
if (/[A-Z]/.test(password)) fuerza++;
|
||||
if (/[a-z]/.test(password)) fuerza++;
|
||||
if (/[0-9]/.test(password)) fuerza++;
|
||||
if (/[^A-Za-z0-9]/.test(password)) fuerza++;
|
||||
|
||||
switch (true) {
|
||||
case fuerza < 3:
|
||||
mensaje = 'Débil';
|
||||
clase = 'text-danger';
|
||||
break;
|
||||
case fuerza < 5:
|
||||
mensaje = 'Regular';
|
||||
clase = 'text-warning';
|
||||
break;
|
||||
default:
|
||||
mensaje = 'Fuerte';
|
||||
clase = 'text-success';
|
||||
}
|
||||
|
||||
indicador.innerHTML = `<i class="fas fa-shield-alt me-1"></i>Fortaleza: <span class="${clase}">${mensaje}</span>`;
|
||||
}
|
||||
|
||||
// Validar coincidencia de contraseñas
|
||||
function validarCoincidencia() {
|
||||
const coincidencia = document.getElementById('passwordMatch');
|
||||
if (!coincidencia) return;
|
||||
|
||||
const nueva = inputNueva.value;
|
||||
const confirmar = inputConfirmar.value;
|
||||
|
||||
if (confirmar && nueva !== confirmar) {
|
||||
coincidencia.innerHTML = '<i class="fas fa-times text-danger me-1"></i><span class="text-danger">Las contraseñas no coinciden</span>';
|
||||
inputConfirmar.classList.add('is-invalid');
|
||||
} else if (confirmar && nueva === confirmar) {
|
||||
coincidencia.innerHTML = '<i class="fas fa-check text-success me-1"></i><span class="text-success">Las contraseñas coinciden</span>';
|
||||
inputConfirmar.classList.remove('is-invalid');
|
||||
inputConfirmar.classList.add('is-valid');
|
||||
} else {
|
||||
coincidencia.innerHTML = '';
|
||||
inputConfirmar.classList.remove('is-invalid', 'is-valid');
|
||||
}
|
||||
}
|
||||
|
||||
// Deshabilitar formulario tras éxito
|
||||
function deshabilitarFormulario() {
|
||||
inputActual.disabled = true;
|
||||
inputNueva.disabled = true;
|
||||
inputConfirmar.disabled = true;
|
||||
btnCambiar.disabled = true;
|
||||
btnCambiar.classList.add('success');
|
||||
btnCambiar.innerHTML = '<i class="fas fa-check me-2"></i>Contraseña cambiada exitosamente';
|
||||
|
||||
toggleButtons.forEach(btn => btn.disabled = true);
|
||||
}
|
||||
|
||||
// Funciones de utilidad para mensajes
|
||||
function mostrarMensaje(texto, tipo) {
|
||||
mensaje.innerHTML = `<div class="${tipo} fade-in">${texto}</div>`;
|
||||
mensaje.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
|
||||
}
|
||||
|
||||
function mostrarError(texto) {
|
||||
mostrarMensaje(`<i class="fas fa-exclamation-triangle me-2"></i>${texto}`, 'text-danger');
|
||||
}
|
||||
|
||||
function mostrarExito(texto) {
|
||||
mostrarMensaje(`<i class="fas fa-check-circle me-2"></i>${texto}`, 'text-success');
|
||||
}
|
||||
|
||||
function mostrarInfo(texto) {
|
||||
mostrarMensaje(`<i class="fas fa-info-circle me-2"></i>${texto}`, 'text-info');
|
||||
}
|
||||
|
||||
function limpiarMensajes() {
|
||||
mensaje.innerHTML = '';
|
||||
}
|
||||
|
||||
// Manejar tecla Enter
|
||||
document.addEventListener('keypress', function(e) {
|
||||
if (e.key === 'Enter' && !btnCambiar.disabled) {
|
||||
form.dispatchEvent(new Event('submit'));
|
||||
}
|
||||
});
|
||||
|
||||
// Prevenir copiar/pegar en campos de contraseña (opcional)
|
||||
[inputActual, inputNueva, inputConfirmar].forEach(input => {
|
||||
input.addEventListener('paste', function(e) {
|
||||
// Permitir paste pero limpiar espacios
|
||||
setTimeout(() => {
|
||||
this.value = this.value.trim();
|
||||
}, 1);
|
||||
});
|
||||
});
|
||||
});
|
||||
</script>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
573
views/reset/verificar_codigo.php
Normal file
573
views/reset/verificar_codigo.php
Normal file
@@ -0,0 +1,573 @@
|
||||
<?php
|
||||
include __DIR__ . '/../partials/sidebar_configuracion.php';
|
||||
|
||||
$dos_factores_estado = obtenerEstadoDosFactores();
|
||||
?>
|
||||
<!DOCTYPE html>
|
||||
<html lang="es">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>👮 Opciones de Seguridad</title>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
|
||||
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.2/sweetalert.min.js"></script>
|
||||
<style>
|
||||
body { font-family: 'Segoe UI', sans-serif; background-color: #f4f6f9; }
|
||||
.sidebar { width: 220px; height: 100vh; background-color: #343a40; position: fixed; top: 0; left: 0; padding-top: 56px; z-index: 1040; }
|
||||
.sidebar .nav-link { font-weight: bold; color: white; transition: all 0.3s ease; }
|
||||
.sidebar .nav-link:hover,
|
||||
.sidebar .nav-link.active { background-color: #495057; color: #fff; }
|
||||
.content { margin-top: 56px; padding: 40px 20px; position: relative; z-index: 1; background-color: #f4f6f9; transition: margin-left 0.3s ease; }
|
||||
.navbar { position: fixed; top: 0; width: 100%; z-index: 1050; }
|
||||
/* A partir de dispositivos medianos (>=768px), deja espacio lateral */
|
||||
@media (min-width: 768px) { .content { margin-left: 250px; /* Ancho del sidebar */ } }
|
||||
/* En móviles, sin margen lateral */
|
||||
@media (max-width: 767.98px) {
|
||||
.content { margin-left: 0; }
|
||||
.sidebar .nav-link { font-weight: normal; color: #343a40; background-color: transparent; }
|
||||
.sidebar .nav-link:hover,
|
||||
.sidebar .nav-link.active { background-color: #e9ecef; color: #212529; }
|
||||
.login-container { width: 95%; padding: 30PX 20px; }
|
||||
}
|
||||
.card { border-radius: 12px; }
|
||||
.btn i { font-family: "Font Awesome 6 Free", sans-serif; margin-right: 0.5rem; }
|
||||
.btn { font-family: 'Segoe UI', sans-serif; }
|
||||
/* Contenedor de fondo semitransparente para las vistas */
|
||||
.overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.5); z-index: 9999; }
|
||||
.login-container { position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); max-width: 420px; width: 90%;
|
||||
background: white; padding: 40px; border-radius: 12px; box-shadow: 0 10px 25px rgba(0, 0, 0, 0.08); z-index: 10000; margin: 0; }
|
||||
.form-control { border-radius: 6px; transition: all 0.3s ease; }
|
||||
.form-control.error { border-color: #dc3545; background-color: #fff5f5; animation: shake 0.5s ease-in-out; }
|
||||
.form-control.success { border-color: #28a745; background-color: #f8fff9; }
|
||||
#mensaje { transition: all 0.3s ease; min-height: 24px; }
|
||||
#btnReenviarRespaldo { background: none; border: none; color: <?= $color1 ?>; text-decoration: underline; cursor: pointer; font-size: 14px; padding: 0; transition: color 0.3s ease; }
|
||||
#btnReenviarRespaldo:hover { color: <?= $color2 ?>; }
|
||||
#btnReenviarRespaldo:disabled { color: #ccc; cursor: not-allowed; text-decoration: none; }
|
||||
.btn:disabled { opacity: 0.6; cursor: not-allowed; }
|
||||
.loading { position: relative; pointer-events: none; }
|
||||
.loading::after { content: ''; position: absolute; top: 50%; left: 50%; width: 20px; height: 20px; border: 2px solid transparent; border-top: 2px solid #fff; border-radius: 50%; animation: spin 1s linear infinite; transform: translate(-50%, -50%); }
|
||||
@keyframes shake {
|
||||
0%, 100% { transform: translateX(0); }
|
||||
25% { transform: translateX(-5px); }
|
||||
75% { transform: translateX(5px); }
|
||||
}
|
||||
@keyframes spin {
|
||||
0% { transform: translate(-50%, -50%) rotate(0deg); }
|
||||
100% { transform: translate(-50%, -50%) rotate(360deg); }
|
||||
}
|
||||
@keyframes fadeIn {
|
||||
from { opacity: 0; transform: translateY(-10px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
.fade-in { animation: fadeIn 0.3s ease-out; }
|
||||
@media (max-height: 600px) { footer { position: static !important; } }
|
||||
/* Estilos para input de código */
|
||||
#codigo { font-size: 18px; letter-spacing: 3px; text-align: center; font-weight: bold; }
|
||||
.input-group { position: relative; }
|
||||
.clear-input { position: absolute; right: 10px; top: 50%; transform: translateY(-50%); background: none; border: none; color: #ccc; cursor: pointer; z-index: 5; display: none; }
|
||||
.clear-input:hover { color: #666; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<!-- Overlay (fondo semitransparente) que cubre la pantalla -->
|
||||
<div class="overlay"></div>
|
||||
|
||||
<!-- Formulario de validación de código -->
|
||||
<div class="login-container">
|
||||
<h4 class="mb-4 text-center text-dark">Verifica tu código</h4>
|
||||
<p class="text-muted text-center mb-4">
|
||||
<i class="fas fa-envelope me-2"></i>
|
||||
Hemos enviado un código de 6 dígitos a tu correo electrónico
|
||||
</p>
|
||||
|
||||
<!-- Formulario para verificar el código -->
|
||||
<form id="formCodigo" action="/IMPORTADORES/reset/verificarCodigoInterno" method="POST">
|
||||
<div class="mb-3">
|
||||
<label class="form-label" for="codigo">
|
||||
<i class="fas fa-key me-2"></i>Código de verificación
|
||||
</label>
|
||||
<div class="input-group">
|
||||
<input type="text" id="codigo" name="codigo" class="form-control" required pattern="\d{6}" maxlength="6" placeholder="000000" autocomplete="off" inputmode="numeric">
|
||||
<button type="button" class="clear-input" id="clearCode" title="Limpiar código">
|
||||
<i class="fas fa-times"></i>
|
||||
</button>
|
||||
</div>
|
||||
<div class="form-text">
|
||||
<i class="fas fa-info-circle me-1"></i>
|
||||
Ingresa el código de 6 dígitos que recibiste por correo
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button type="submit" id="btnVerificar" class="btn btn-success w-100">
|
||||
<i class="fas fa-check me-2"></i>Verificar código
|
||||
</button>
|
||||
|
||||
<!-- Botón para enviar el código al correo de respaldo-->
|
||||
<div class="text-center mt-3">
|
||||
<button type="button" id="btnReenviarRespaldo" title="Enviar código al correo de respaldo">
|
||||
<i class="fas fa-paper-plane me-1"></i>
|
||||
¿No tienes acceso al correo? Reenviar al correo de respaldo
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<!-- Mostrar mensajes -->
|
||||
<div id="mensaje" class="mt-3 text-center fw-bold">
|
||||
<?php if (isset($_SESSION['codigo_error'])): ?>
|
||||
<div class="text-danger fade-in">
|
||||
<i class="fas fa-exclamation-triangle me-2"></i>
|
||||
<?= $_SESSION['codigo_error'] ?>
|
||||
</div>
|
||||
<?php unset($_SESSION['codigo_error']); ?>
|
||||
<?php elseif (isset($_SESSION['codigo_exito'])): ?>
|
||||
<div class="text-success fade-in">
|
||||
<i class="fas fa-check-circle me-2"></i>
|
||||
<?= $_SESSION['codigo_exito'] ?>
|
||||
</div>
|
||||
<?php unset($_SESSION['codigo_exito']); ?>
|
||||
<?php elseif (isset($_SESSION['conexion_error'])): ?>
|
||||
<div class="text-danger fade-in">
|
||||
<i class="fas fa-exclamation-triangle me-2"></i>
|
||||
<?= $_SESSION['conexion_error'] ?>
|
||||
</div>
|
||||
<?php unset($_SESSION['conexion_error']); ?>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
|
||||
<!-- Contador de intentos -->
|
||||
<div id="intentosInfo" class="mt-2 text-center text-muted" style="font-size: 12px;">
|
||||
<!-- Se llenará dinámicamente -->
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="content">
|
||||
<h4 class="mb-4">👮 Opciones de Seguridad</h4>
|
||||
<div class="row g-3">
|
||||
|
||||
<!-- Autenticacin de dos factores -->
|
||||
<div class="col-md-6">
|
||||
<div class="card shadow-sm p-3">
|
||||
<h4 class="mb-4 text-dark">Autenticación de dos factores</h4>
|
||||
<p>Al activar esta funcionalidad, blindas el acceso a tu cuenta, recibiras un código de acceso a tu correo electrónico para confirmar identidad.</p>
|
||||
<form method="POST" action="/IMPORTADORES/seguridad/autenticacionDosFactores">
|
||||
<div class="form-check form-switch mb-3">
|
||||
<input type="checkbox" name="dos_factores" id="dos_factores" class="form-check-input"
|
||||
<?php echo ($dos_factores_estado == 1) ? "checked" : ""; ?>>
|
||||
<label class="form-check-label" for="dos_factores">
|
||||
<?php echo ($dos_factores_estado == 1) ? "Activo" : "Inactivo"; ?>
|
||||
</label>
|
||||
</div>
|
||||
<button type="submit" class="btn btn-primary"><i class="fas fa-floppy-disk"></i>Guardar configuración</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Cambiar contraseña -->
|
||||
<div class="col-md-6">
|
||||
<div class="card shadow-sm p-3">
|
||||
<h4 class="mb-4 text-dark">Cambiar contraseña</h4>
|
||||
<p>Al actualizar tu contraseña, refuerzas la seguridad de tu cuenta. Te recomendamos usar una combinación de letras, números y símbolos para mayor seguridad.</p><br><br>
|
||||
<a href="/IMPORTADORES/reset/changePassword" class="btn btn-primary">Cambiar contraseña</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Correo adicional (extra) -->
|
||||
<div class="col-md-6">
|
||||
<div class="card shadow-sm p-3">
|
||||
<h4 class="mb-4 text-dark">Recibe notificaciones</h4>
|
||||
<p>Agrega un correo adicional para recibir notificaciones.</p>
|
||||
<?php if (!empty($correos['correo_extra'])): ?>
|
||||
<p><code><?= htmlspecialchars($correos['correo_extra']) ?></code></p>
|
||||
<!-- Formulario para eliminar -->
|
||||
<form method="POST" action="/IMPORTADORES/seguridad/eliminarCorreoExtra" id="form-eliminar-extra" class="mt-2 hide"></form>
|
||||
<form method="POST" action="/IMPORTADORES/seguridad/modificarCorreoExtra">
|
||||
<div class="mb-3">
|
||||
<input type="email" name="email-extra" class="form-control" value="" placeholder="Actualizar correo adicional" required>
|
||||
</div>
|
||||
<div class="d-flex gap-2">
|
||||
<button type="submit" class="btn btn-success">
|
||||
<i class="fas fa-edit"></i>Actualizar
|
||||
</button>
|
||||
<button type="button" class="btn btn-danger" onclick="confirmarEliminacion('extra')">
|
||||
<i class="fas fa-trash"></i> Eliminar correo
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
<?php else: ?>
|
||||
<form method="POST" action="/IMPORTADORES/seguridad/correoExtra">
|
||||
<div class="mb-3">
|
||||
<input type="email" name="email-extra" class="form-control" placeholder="Correo adicional" required>
|
||||
</div>
|
||||
<button type="submit" class="btn btn-primary"><i class="fas fa-envelope"></i>Registrar</button>
|
||||
</form>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Correo de Respaldo -->
|
||||
<div class="col-md-6">
|
||||
<div class="card shadow-sm p-3">
|
||||
<h4 class="mb-4 text-dark">Correo de respaldo</h4>
|
||||
<p>Agrega un correo de respaldo para reuperación de tu cuenta.</p>
|
||||
<?php if (!empty($correos['correo_respaldo'])): ?>
|
||||
<p><code><?= htmlspecialchars($correos['correo_respaldo']) ?></code></p>
|
||||
<!-- Formulario para eliminar -->
|
||||
<form method="POST" action="/IMPORTADORES/seguridad/eliminarCorreoRespaldo" id="form-eliminar-respaldo" class="mt-2 hide"></form>
|
||||
<form method="POST" action="/IMPORTADORES/seguridad/modificarCorreoRspaldo">
|
||||
<div class="mb-3">
|
||||
<input type="email" name="email-respaldo" class="form-control" value="" placeholder="Actualizar correo de respaldo" required>
|
||||
</div>
|
||||
<button type="submit" class="btn btn-success">
|
||||
<i class="fas fa-edit"></i>Actualizar
|
||||
</button>
|
||||
<button type="button" class="btn btn-danger" onclick="confirmarEliminacion('respaldo')">
|
||||
<i class="fas fa-trash"></i> Eliminar correo
|
||||
</button>
|
||||
</form>
|
||||
<?php else: ?>
|
||||
<form method="POST" action="/IMPORTADORES/seguridad/correoRespaldo">
|
||||
<div class="mb-3">
|
||||
<input type="email" name="email-respaldo" class="form-control" placeholder="Correo de respaldo" required>
|
||||
</div>
|
||||
<button type="submit" class="btn btn-primary"><i class="fas fa-envelope"></i>Registrar</button>
|
||||
</form>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
document.addEventListener('DOMContentLoaded', function () {
|
||||
const form = document.getElementById('formCodigo');
|
||||
const mensaje = document.getElementById('mensaje');
|
||||
const inputCodigo = document.getElementById('codigo');
|
||||
const btnVerificar = document.getElementById('btnVerificar');
|
||||
const btnReenviar = document.getElementById('btnReenviarRespaldo');
|
||||
const clearBtn = document.getElementById('clearCode');
|
||||
const intentosInfo = document.getElementById('intentosInfo');
|
||||
|
||||
let intentosRealizados = 0;
|
||||
const maxIntentos = 3;
|
||||
|
||||
// Auto-focus en el input al cargar
|
||||
inputCodigo.focus();
|
||||
|
||||
// Mostrar/ocultar botón de limpiar
|
||||
inputCodigo.addEventListener('input', function() {
|
||||
clearBtn.style.display = this.value.length > 0 ? 'block' : 'none';
|
||||
|
||||
// Limpiar mensajes previos
|
||||
limpiarMensajes();
|
||||
|
||||
// Remover clases de error/éxito
|
||||
inputCodigo.classList.remove('error', 'success');
|
||||
|
||||
// Solo permitir números
|
||||
this.value = this.value.replace(/[^0-9]/g, '');
|
||||
|
||||
// Actualizar contador visual
|
||||
actualizarContadorVisual();
|
||||
});
|
||||
|
||||
// Limpiar input
|
||||
clearBtn.addEventListener('click', function() {
|
||||
inputCodigo.value = '';
|
||||
inputCodigo.focus();
|
||||
clearBtn.style.display = 'none';
|
||||
limpiarMensajes();
|
||||
inputCodigo.classList.remove('error', 'success');
|
||||
});
|
||||
|
||||
// Permitir solo números en tiempo real
|
||||
inputCodigo.addEventListener('keypress', function(e) {
|
||||
if (!/[0-9]/.test(e.key) && !['Backspace', 'Delete', 'Tab', 'Enter'].includes(e.key)) {
|
||||
e.preventDefault();
|
||||
}
|
||||
});
|
||||
|
||||
// Auto-envío cuando se completen 6 dígitos (opcional)
|
||||
inputCodigo.addEventListener('input', function() {
|
||||
if (this.value.length === 6) {
|
||||
// Opcional: enviar automáticamente después de un breve delay
|
||||
setTimeout(() => form.dispatchEvent(new Event('submit')), 500);
|
||||
}
|
||||
});
|
||||
|
||||
// Manejo del formulario
|
||||
form.addEventListener('submit', function(e) {
|
||||
e.preventDefault();
|
||||
|
||||
const codigo = inputCodigo.value.trim();
|
||||
if (!validarCodigo(codigo)) return;
|
||||
|
||||
enviarCodigo(codigo);
|
||||
});
|
||||
|
||||
// Validación del código
|
||||
function validarCodigo(codigo) {
|
||||
if (!codigo) {
|
||||
mostrarError("❌ Por favor, ingresa el código.");
|
||||
return false;
|
||||
}
|
||||
if (codigo.length !== 6) {
|
||||
mostrarError("❌ El código debe tener exactamente 6 dígitos.");
|
||||
inputCodigo.classList.add('error');
|
||||
return false;
|
||||
}
|
||||
if (!/^\d{6}$/.test(codigo)) {
|
||||
mostrarError("❌ El código solo debe contener números.");
|
||||
inputCodigo.classList.add('error');
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// 1. SOLUCIÓN PARA EL CONTADOR DE INTENTOS
|
||||
// REEMPLAZA tu función enviarCodigo con esta versión de debug:
|
||||
function enviarCodigo(codigo) {
|
||||
btnVerificar.disabled = true;
|
||||
btnVerificar.classList.add('loading');
|
||||
btnVerificar.innerHTML = '<span style="opacity: 0;">Verificando...</span>';
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append('codigo', codigo);
|
||||
|
||||
fetch('/IMPORTADORES/reset/verificarCodigoInterno', {
|
||||
method: 'POST',
|
||||
body: formData,
|
||||
credentials: 'same-origin'
|
||||
})
|
||||
.then(response => {
|
||||
console.log('Status:', response.status);
|
||||
console.log('Content-Type:', response.headers.get('content-type'));
|
||||
|
||||
// SIEMPRE obtener el texto primero para debug
|
||||
return response.text();
|
||||
})
|
||||
.then(text => {
|
||||
console.log('Respuesta completa del servidor:');
|
||||
console.log(text);
|
||||
|
||||
// Mostrar los primeros 500 caracteres en la consola
|
||||
console.log('Primeros 500 caracteres:', text.substring(0, 500));
|
||||
|
||||
// Intentar parsear como JSON
|
||||
try {
|
||||
const data = JSON.parse(text);
|
||||
console.log('JSON parseado exitosamente:', data);
|
||||
|
||||
// Procesar respuesta normal
|
||||
if (data.blocked) {
|
||||
mostrarError(data.message);
|
||||
setTimeout(() => {
|
||||
window.location.href = data.redirect;
|
||||
}, 4000);
|
||||
return;
|
||||
}
|
||||
|
||||
if (data.success === true) {
|
||||
mostrarExito(data.message);
|
||||
inputCodigo.classList.add('success');
|
||||
inputCodigo.disabled = true;
|
||||
|
||||
setTimeout(() => {
|
||||
window.location.href = '/IMPORTADORES/reset/cambiarPasswordInternoView';
|
||||
}, 1500);
|
||||
|
||||
} else {
|
||||
manejarCodigoIncorrecto(data);
|
||||
}
|
||||
|
||||
} catch (parseError) {
|
||||
console.error('Error al parsear JSON:', parseError);
|
||||
console.error('Texto que causó el error:', text);
|
||||
|
||||
// Mostrar error al usuario
|
||||
mostrarError("❌ Error del servidor. Revisa la consola para más detalles.");
|
||||
inputCodigo.classList.add('error');
|
||||
limpiarYEnfocarInput();
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Error de red:', error);
|
||||
mostrarError("❌ Error de conexión. Intenta nuevamente.");
|
||||
inputCodigo.classList.add('error');
|
||||
limpiarYEnfocarInput();
|
||||
})
|
||||
.finally(() => {
|
||||
btnVerificar.disabled = false;
|
||||
btnVerificar.classList.remove('loading');
|
||||
btnVerificar.innerHTML = '<i class="fas fa-check me-2"></i>Verificar código';
|
||||
});
|
||||
}
|
||||
|
||||
// 2. FUNCIÓN CORREGIDA PARA MANEJAR CÓDIGO INCORRECTO
|
||||
function manejarCodigoIncorrecto(data) {
|
||||
// USAR intentos del servidor, no incrementar localmente
|
||||
if (data.intentos_restantes !== undefined) {
|
||||
const restantes = data.intentos_restantes;
|
||||
intentosRealizados = maxIntentos - restantes;
|
||||
} else {
|
||||
// Fallback: incrementar localmente solo si no hay datos del servidor
|
||||
intentosRealizados++;
|
||||
}
|
||||
|
||||
mostrarError(data.message);
|
||||
inputCodigo.classList.add('error');
|
||||
|
||||
limpiarYEnfocarInput();
|
||||
actualizarContadorIntentos();
|
||||
|
||||
if (data.blocked || (data.intentos_restantes !== undefined && data.intentos_restantes <= 0)) {
|
||||
bloquearFormulario();
|
||||
}
|
||||
}
|
||||
|
||||
// 3. FUNCIÓN ACTUALIZADA PARA MOSTRAR INTENTOS
|
||||
function actualizarContadorIntentos() {
|
||||
if (intentosRealizados > 0) {
|
||||
const restantes = Math.max(0, maxIntentos - intentosRealizados); // Evitar negativos
|
||||
if (restantes > 0) {
|
||||
intentosInfo.innerHTML = `
|
||||
<i class="fas fa-exclamation-triangle text-warning me-1"></i>
|
||||
Intentos restantes: <strong>${restantes}</strong> de ${maxIntentos}
|
||||
`;
|
||||
} else {
|
||||
intentosInfo.innerHTML = `
|
||||
<i class="fas fa-ban text-danger me-1"></i>
|
||||
<span class="text-danger">Sin intentos restantes</span>
|
||||
`;
|
||||
}
|
||||
intentosInfo.classList.add('fade-in');
|
||||
}
|
||||
}
|
||||
|
||||
// Limpiar input y enfocar
|
||||
function limpiarYEnfocarInput() {
|
||||
setTimeout(() => {
|
||||
inputCodigo.value = '';
|
||||
inputCodigo.classList.remove('error');
|
||||
inputCodigo.focus();
|
||||
clearBtn.style.display = 'none';
|
||||
}, 1500); // Esperar 1.5 segundos antes de limpiar
|
||||
}
|
||||
|
||||
// Actualizar contador visual
|
||||
function actualizarContadorVisual() {
|
||||
const longitud = inputCodigo.value.length;
|
||||
if (longitud > 0) {
|
||||
inputCodigo.setAttribute('placeholder', '0'.repeat(6 - longitud) + inputCodigo.value);
|
||||
} else {
|
||||
inputCodigo.setAttribute('placeholder', '000000');
|
||||
}
|
||||
}
|
||||
|
||||
// Actualizar contador de intentos
|
||||
function actualizarContadorIntentos() {
|
||||
if (intentosRealizados > 0) {
|
||||
const restantes = maxIntentos - intentosRealizados;
|
||||
intentosInfo.innerHTML = `
|
||||
<i class="fas fa-exclamation-triangle text-warning me-1"></i>
|
||||
Intentos restantes: <strong>${restantes}</strong> de ${maxIntentos}
|
||||
`;
|
||||
intentosInfo.classList.add('fade-in');
|
||||
}
|
||||
}
|
||||
|
||||
// Bloquear formulario cuando se exceden intentos
|
||||
function bloquearFormulario() {
|
||||
inputCodigo.disabled = true;
|
||||
btnVerificar.disabled = true;
|
||||
btnReenviar.disabled = true;
|
||||
|
||||
intentosInfo.innerHTML = `
|
||||
<i class="fas fa-ban text-danger me-1"></i>
|
||||
<span class="text-danger">Código bloqueado por seguridad</span>
|
||||
`;
|
||||
|
||||
// Redirigir a solicitar nuevo código después de 5 segundos
|
||||
setTimeout(() => {
|
||||
window.location.href = '/IMPORTADORES/reset/enviarCodigoInterno';
|
||||
}, 5000);
|
||||
}
|
||||
|
||||
// Funciones de utilidad para mensajes
|
||||
function mostrarMensaje(texto, tipo) {
|
||||
mensaje.innerHTML = `<div class="${tipo} fade-in">${texto}</div>`;
|
||||
mensaje.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
|
||||
}
|
||||
|
||||
function mostrarError(texto) {
|
||||
mostrarMensaje(`<i class="fas fa-exclamation-triangle me-2"></i>${texto}`, 'text-danger');
|
||||
}
|
||||
|
||||
function mostrarExito(texto) {
|
||||
mostrarMensaje(`<i class="fas fa-check-circle me-2"></i>${texto}`, 'text-success');
|
||||
}
|
||||
|
||||
function mostrarInfo(texto) {
|
||||
mostrarMensaje(`<i class="fas fa-info-circle me-2"></i>${texto}`, 'text-info');
|
||||
}
|
||||
|
||||
function limpiarMensajes() {
|
||||
mensaje.innerHTML = '';
|
||||
}
|
||||
|
||||
// Manejo del botón de reenvío
|
||||
btnReenviar.addEventListener("click", function() {
|
||||
const btnOriginalText = this.innerHTML;
|
||||
|
||||
// Deshabilitar botón temporalmente
|
||||
this.disabled = true;
|
||||
this.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>Enviando...';
|
||||
|
||||
fetch("/IMPORTADORES/reset/reenviarCodigo", {
|
||||
method: "POST",
|
||||
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
|
||||
body: "accion=reenviarCodigo"
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
mostrarInfo(data.message);
|
||||
|
||||
// Habilitar botón después de 30 segundos
|
||||
setTimeout(() => {
|
||||
this.disabled = false;
|
||||
this.innerHTML = btnOriginalText;
|
||||
}, 30000);
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Error:', error);
|
||||
mostrarError("❌ Error al reenviar código.");
|
||||
|
||||
// Restaurar botón en caso de error
|
||||
this.disabled = false;
|
||||
this.innerHTML = btnOriginalText;
|
||||
});
|
||||
});
|
||||
|
||||
// Manejar tecla Enter en cualquier parte del formulario
|
||||
document.addEventListener('keypress', function(e) {
|
||||
if (e.key === 'Enter' && !btnVerificar.disabled) {
|
||||
form.dispatchEvent(new Event('submit'));
|
||||
}
|
||||
});
|
||||
|
||||
// Prevenir paste de contenido no numérico
|
||||
inputCodigo.addEventListener('paste', function(e) {
|
||||
e.preventDefault();
|
||||
const paste = (e.clipboardData || window.clipboardData).getData('text');
|
||||
const numericPaste = paste.replace(/[^0-9]/g, '').substring(0, 6);
|
||||
this.value = numericPaste;
|
||||
this.dispatchEvent(new Event('input'));
|
||||
});
|
||||
});
|
||||
</script>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -33,15 +33,19 @@ $dos_factores_estado = obtenerEstadoDosFactores();
|
||||
.card { border-radius: 12px; }
|
||||
.btn i { font-family: "Font Awesome 6 Free", sans-serif; margin-right: 0.5rem; }
|
||||
.btn { font-family: 'Segoe UI', sans-serif; }
|
||||
.modal-header.bg-primary { background: linear-gradient(135deg, #003366, #0055A5) !important; color: white; }
|
||||
.modal-header.bg-success { background: linear-gradient(135deg, #28a745, #20c997) !important; color: white; }
|
||||
.codigo-input { text-align: center; font-size: 1.5rem; letter-spacing: 0.5rem; font-weight: bold; }
|
||||
.intentos-restantes { color: #dc3545; font-weight: bold; }
|
||||
.password-strength { height: 4px; border-radius: 2px; margin-top: 5px; transition: all 0.3s ease; }
|
||||
.strength-weak { background-color: #dc3545; }
|
||||
.strength-medium { background-color: #ffc107; }
|
||||
.strength-strong { background-color: #28a745; }
|
||||
.btn-loading { pointer-events: none; opacity: 0.6; }
|
||||
/* Fix para z-index del modal */
|
||||
.modal { z-index: 9999 !important; }
|
||||
.modal-backdrop { z-index: 9998 !important; }
|
||||
/* Estilos adicionales para mejorar la apariencia del modal */
|
||||
.modal-content { border: none; border-radius: 15px; overflow: hidden; }
|
||||
.modal-header { border-bottom: none; padding: 20px 25px 15px; }
|
||||
.modal-body { padding: 25px; }
|
||||
.modal-footer { border-top: none; padding: 15px 25px 25px; }
|
||||
.btn { border-radius: 8px; padding: 10px 20px; font-weight: 500; }
|
||||
.alert-info { background-color: #e3f2fd; border-color: #bbdefb; color: #1565c0; border-radius: 8px; }
|
||||
/* Animación suave para el modal */
|
||||
.modal.fade .modal-dialog { transform: translate(0, -50px); transition: transform 0.3s ease-out; }
|
||||
.modal.show .modal-dialog { transform: translate(0, 0); }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
@@ -68,7 +72,18 @@ $dos_factores_estado = obtenerEstadoDosFactores();
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="col-md-6 hide"></div>
|
||||
<!-- Cambiar contraseña -->
|
||||
<div class="col-md-6">
|
||||
<div class="card shadow-sm p-3">
|
||||
<h4 class="mb-4 text-dark">Cambiar contraseña</h4>
|
||||
<p>Al actualizar tu contraseña, refuerzas la seguridad de tu cuenta. Te recomendamos usar una combinación de letras, números y símbolos para mayor seguridad.</p><br>
|
||||
<form>
|
||||
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#modalConfirmarCambio">
|
||||
<i class="fas fa-key"></i>Cambiar contraseña
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Correo adicional (extra) -->
|
||||
<div class="col-md-6">
|
||||
@@ -137,69 +152,95 @@ $dos_factores_estado = obtenerEstadoDosFactores();
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Modal de confirmación -->
|
||||
<div class="modal fade" id="modalConfirmarCambio" tabindex="-1" aria-labelledby="modalConfirmarCambioLabel" aria-hidden="true">
|
||||
<div class="modal-dialog modal-dialog-centered">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header bg-primary text-white">
|
||||
<h5 class="modal-title" id="modalConfirmarCambioLabel">
|
||||
<i class="fas fa-exclamation-triangle me-2"></i>
|
||||
Confirmar cambio de contraseña
|
||||
</h5>
|
||||
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
|
||||
</div>
|
||||
<div class="modal-body text-center">
|
||||
<div class="mb-3">
|
||||
<i class="fas fa-shield-alt text-warning" style="font-size: 3rem;"></i>
|
||||
</div>
|
||||
<h5 class="mb-3">¿Estás seguro de cambiar tu contraseña?</h5>
|
||||
<p class="text-muted">
|
||||
Se enviará un código de verificación a tu correo electrónico para confirmar el cambio de contraseña.
|
||||
</p>
|
||||
<div class="alert alert-info">
|
||||
<small>
|
||||
<i class="fas fa-info-circle me-1"></i>
|
||||
El código expirará en 10 minutos
|
||||
</small>
|
||||
</div>
|
||||
</div>
|
||||
<div class="modal-footer justify-content-center">
|
||||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
|
||||
<i class="fas fa-times me-1"></i>
|
||||
Cancelar
|
||||
</button>
|
||||
<form method="POST" action="/IMPORTADORES/reset/enviarCodigoInterno" style="display: inline;">
|
||||
<button type="submit" class="btn btn-primary">
|
||||
<i class="fas fa-check me-1"></i>
|
||||
Sí, estoy seguro
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const chk = document.getElementById('dos_factores');
|
||||
const label = document.querySelector('label[for="dos_factores"]');
|
||||
|
||||
chk.addEventListener('change', () => {
|
||||
label.textContent = chk.checked ? 'Activo' : 'Inactivo';
|
||||
});
|
||||
|
||||
chk.addEventListener('change', () => { label.textContent = chk.checked ? 'Activo' : 'Inactivo'; });
|
||||
// Función para confirmar eliminación con SweetAlert
|
||||
function confirmarEliminacion(tipo) {
|
||||
const mensajes = {
|
||||
'extra': {
|
||||
titulo: '¿Eliminar correo adicional?',
|
||||
texto: 'No podrás recibir notificaciones en este correo.',
|
||||
confirmado: 'Correo adicional eliminado',
|
||||
form: 'form-eliminar-extra'
|
||||
},
|
||||
'respaldo': {
|
||||
titulo: '¿Eliminar correo de respaldo?',
|
||||
texto: 'No podrás recuperar tu cuenta con este correo.',
|
||||
confirmado: 'Correo de respaldo eliminado',
|
||||
form: 'form-eliminar-respaldo'
|
||||
}
|
||||
'extra': { titulo: '¿Eliminar correo adicional?', texto: 'No podrás recibir notificaciones en este correo.', confirmado: 'Correo adicional eliminado', form: 'form-eliminar-extra' },
|
||||
'respaldo': { titulo: '¿Eliminar correo de respaldo?', texto: 'No podrás recuperar tu cuenta con este correo.', confirmado: 'Correo de respaldo eliminado', form: 'form-eliminar-respaldo' }
|
||||
};
|
||||
|
||||
const config = mensajes[tipo];
|
||||
|
||||
swal({
|
||||
title: config.titulo,
|
||||
text: config.texto,
|
||||
icon: "warning",
|
||||
buttons: {
|
||||
cancel: {
|
||||
text: "Cancelar",
|
||||
visible: true,
|
||||
className: "btn-secondary"
|
||||
},
|
||||
confirm: {
|
||||
text: "Sí, eliminar",
|
||||
className: "btn-danger"
|
||||
}
|
||||
},
|
||||
dangerMode: true,
|
||||
swal({ title: config.titulo, text: config.texto, icon: "warning", buttons: {
|
||||
cancel: { text: "Cancelar", visible: true, className: "btn-secondary" },
|
||||
confirm: { text: "Sí, eliminar", className: "btn-danger" }
|
||||
}, dangerMode: true,
|
||||
})
|
||||
.then((eliminar) => {
|
||||
if (eliminar) {
|
||||
// Mostrar mensaje de éxito y enviar formulario
|
||||
swal({
|
||||
title: "¡Eliminado!",
|
||||
text: config.confirmado,
|
||||
icon: "success",
|
||||
timer: 1500,
|
||||
buttons: false
|
||||
});
|
||||
|
||||
swal({ title: "¡Eliminado!", text: config.confirmado, icon: "success", timer: 1500, buttons: false });
|
||||
// Enviar el formulario después de un pequeño delay
|
||||
setTimeout(() => {
|
||||
document.getElementById(config.form).submit();
|
||||
}, 1500);
|
||||
setTimeout(() => { document.getElementById(config.form).submit(); }, 1500);
|
||||
}
|
||||
});
|
||||
}
|
||||
</script>
|
||||
|
||||
<script>
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
const form = document.querySelector('#modalConfirmarCambio form');
|
||||
const submitBtn = form.querySelector('button[type="submit"]');
|
||||
const modal = document.getElementById('modalConfirmarCambio');
|
||||
|
||||
// Agregar efecto de carga al botón de confirmación
|
||||
form.addEventListener('submit', function() {
|
||||
submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i> Enviando...';
|
||||
submitBtn.disabled = true;
|
||||
});
|
||||
|
||||
// Resetear el botón cuando se cierra el modal
|
||||
modal.addEventListener('hidden.bs.modal', function() {
|
||||
submitBtn.innerHTML = '<i class="fas fa-check me-1"></i> Sí, estoy seguro';
|
||||
submitBtn.disabled = false;
|
||||
});
|
||||
});
|
||||
</script>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -51,7 +51,13 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="col-md-6 hide"></div>
|
||||
<!-- Cambiar contraseña -->
|
||||
<div class="col-md-6">
|
||||
<div class="card shadow-sm p-3">
|
||||
<h4 class="mb-4 text-dark">Cambiar contraseña</h4>
|
||||
<p>Al actualizar tu contraseña, refuerzas la seguridad de tu cuenta. Te recomendamos usar una combinación de letras, números y símbolos para mayor seguridad.</p><br>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="col-md-6">
|
||||
<div class="card shadow-sm p-3">
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
<title>➕ Nueva Solicitud de Importación</title>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/choices.js/public/assets/styles/choices.min.css"/>
|
||||
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
|
||||
<link href="https://cdn.datatables.net/1.13.4/css/jquery.dataTables.min.css" rel="stylesheet">
|
||||
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
|
||||
@@ -26,10 +27,20 @@
|
||||
}
|
||||
.card { border-radius: 12px; }
|
||||
.hide { display: none !important; }
|
||||
.alert { top: 75px; left: 275px; right: 50px; position: fixed; z-index: 1050; width: calc(100% - 285px); }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<?php if (!isset($_SESSION['id_agencia_en_uso']) || !$_SESSION['id_agencia_en_uso']): ?>
|
||||
<div class="alert alert-warning mt-4">
|
||||
<h5>⚠️ No tienes una agencia activa vinculada.</h5>
|
||||
<p>Para poder gestionar tus solicitudes de importación, primero debes <strong>vincularte a una agencia</strong>.</p>
|
||||
<a href="/IMPORTADORES/vinculaciones/nuevaVinculacion" class="btn btn-primary">Ir a Vinculaciones</a>
|
||||
</div>
|
||||
<?php return; ?>
|
||||
<?php endif; ?>
|
||||
|
||||
<div class="content">
|
||||
<h4>➕ Nueva Solicitud de Importación</h4>
|
||||
<div class="card p-4 bg-white shadow-sm">
|
||||
|
||||
@@ -9,8 +9,7 @@
|
||||
<!-- Bootstrap CSS -->
|
||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
|
||||
<!-- Choices.js CSS -->
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/choices.js/public/assets/styles/choices.min.css"/>
|
||||
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
|
||||
<link href="https://cdn.datatables.net/1.13.4/css/jquery.dataTables.min.css" rel="stylesheet">
|
||||
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
|
||||
|
||||
@@ -34,10 +34,20 @@
|
||||
}
|
||||
.card { border-radius: 12px; }
|
||||
.status-select:disabled { background-color: #e9ecef; color: #6c757d;}
|
||||
.alert { top: 75px; left: 275px; right: 50px; position: fixed; z-index: 1050; width: calc(100% - 285px); }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<?php if (!isset($_SESSION['id_agencia_en_uso']) || !$_SESSION['id_agencia_en_uso']): ?>
|
||||
<div class="alert alert-warning mt-4">
|
||||
<h5>⚠️ No tienes una agencia activa vinculada.</h5>
|
||||
<p>Para poder gestionar tus solicitudes de importación, primero debes <strong>vincularte a una agencia</strong>.</p>
|
||||
<a href="/IMPORTADORES/vinculaciones/nuevaVinculacion" class="btn btn-primary">Ir a Vinculaciones</a>
|
||||
</div>
|
||||
<?php return; ?>
|
||||
<?php endif; ?>
|
||||
|
||||
<div class="content">
|
||||
<h4>📄 Solicitudes de Importación</h4>
|
||||
<a href="/IMPORTADORES/solicitud_importacion/crear" class="btn btn-success mb-3">➕ Nueva Solicitud</a>
|
||||
|
||||
@@ -117,12 +117,10 @@
|
||||
|
||||
// Mostrar alert de “borrado” al volver de la acción
|
||||
<?php if (isset($_GET['deleted']) && $_GET['deleted']==='ok'): ?>
|
||||
Swal.fire({
|
||||
icon: 'success',
|
||||
title: 'Transportista eliminado',
|
||||
text: 'Ya no aparecerá en tu lista.',
|
||||
confirmButtonColor: '#198754'
|
||||
});
|
||||
Swal.fire({ icon: 'success', title: 'Transportista eliminado', text: 'Ya no aparecerá en tu lista.', confirmButtonColor: '#198754' });
|
||||
<?php endif; ?>
|
||||
<?php if (isset($_GET['edit']) && $_GET['edit'] === 'ok'): ?>
|
||||
Swal.fire({ icon: 'success', title: 'Transportista actualizado', text: 'Los datos fueron modificados correctamente.', confirmButtonColor: '#198754' });
|
||||
<?php endif; ?>
|
||||
</script>
|
||||
|
||||
|
||||
Reference in New Issue
Block a user