298 lines
8.9 KiB
PHP
298 lines
8.9 KiB
PHP
<?php
|
|
|
|
require_once __DIR__ . '/../../config/database.php';
|
|
require_once __DIR__ . '/../helpers/env.php';
|
|
require_once __DIR__ . '/../helpers/crypto.php';
|
|
use PHPMailer\PHPMailer\PHPMailer;
|
|
use PHPMailer\PHPMailer\Exception;
|
|
|
|
|
|
loadEnv();
|
|
|
|
|
|
|
|
session_start();
|
|
|
|
function index() {
|
|
header("Location: /IMPORTADORES/sistemas/login");
|
|
exit;
|
|
}
|
|
|
|
function login() {
|
|
// Si es GET, mostrar el formulario
|
|
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
|
|
include __DIR__ . '/../../views/admin/login_sistemas.php';
|
|
return;
|
|
}
|
|
|
|
// Si es POST, procesar login
|
|
$email = $_POST['email'] ?? '';
|
|
$clave = $_POST['clave'] ?? '';
|
|
|
|
if ($email === 'sistemas@aduanasoft.com.mx' && $clave === 'rootSecure2025!') {
|
|
$_SESSION['usuario_sistemas'] = true;
|
|
header("Location: /IMPORTADORES/sistemas/alta_usuarios");
|
|
} else {
|
|
echo "❌ Acceso denegado.";
|
|
}
|
|
}
|
|
|
|
|
|
function alta_usuarios() {
|
|
if (!($_SESSION['usuario_sistemas'] ?? false)) {
|
|
die("⚠️ No autorizado.");
|
|
}
|
|
|
|
$conn = getConnection();
|
|
$sql = "SELECT * FROM usuarios_sistema ORDER BY creado_en DESC";
|
|
$stmt = sqlsrv_query($conn, $sql);
|
|
|
|
$usuarios = [];
|
|
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
|
|
$usuarios[] = $row;
|
|
}
|
|
|
|
include __DIR__ . '/../../views/admin/alta_usuarios.php';
|
|
}
|
|
|
|
|
|
function guardar_usuario()
|
|
{
|
|
if (!($_SESSION['usuario_sistemas'] ?? false)) {
|
|
die("⚠️ No autorizado.");
|
|
}
|
|
|
|
|
|
$conn = getConnection();
|
|
|
|
// 1. Capturar y validar datos
|
|
$nombre = trim($_POST['nombre'] ?? '');
|
|
$email = trim($_POST['email'] ?? '');
|
|
$password = $_POST['password'] ?? '';
|
|
$tipo = $_POST['tipo_usuario'] ?? '';
|
|
|
|
if (empty($nombre) || empty($email) || empty($password) || empty($tipo)) {
|
|
die("❌ Todos los campos son obligatorios.");
|
|
}
|
|
|
|
if (!in_array($tipo, ['importador', 'agente_aduanal'])) {
|
|
die("❌ Tipo de usuario inválido.");
|
|
}
|
|
|
|
// 2. Encriptar datos sensibles
|
|
$nombre_encrypted = encrypt($nombre);
|
|
$email_encrypted = encrypt($email);
|
|
$password_hash = password_hash($password, PASSWORD_DEFAULT);
|
|
|
|
// 3. Validar duplicado por email encriptado
|
|
$sqlCheck = "SELECT COUNT(*) AS total FROM usuarios_sistema WHERE email = ?";
|
|
$stmtCheck = sqlsrv_query($conn, $sqlCheck, [$email_encrypted]);
|
|
$rowCheck = sqlsrv_fetch_array($stmtCheck, SQLSRV_FETCH_ASSOC);
|
|
if ($rowCheck['total'] > 0) {
|
|
die("❌ Este correo ya está registrado.");
|
|
}
|
|
|
|
// 4. Insertar usuario
|
|
$sqlInsert = "INSERT INTO usuarios_sistema (nombre, email, password_hash, tipo_usuario, activo, creado_en)
|
|
VALUES (?, ?, ?, ?, 1, GETDATE())";
|
|
$params = [$nombre_encrypted, $email_encrypted, $password_hash, $tipo];
|
|
|
|
$stmtInsert = sqlsrv_query($conn, $sqlInsert, $params);
|
|
|
|
if ($stmtInsert === false) {
|
|
die("❌ Error al guardar: " . print_r(sqlsrv_errors(), true));
|
|
}
|
|
|
|
// 5. Redirigir
|
|
header("Location: /IMPORTADORES/sistemas/alta_usuarios");
|
|
exit;
|
|
}
|
|
|
|
|
|
function logout() {
|
|
session_start();
|
|
session_unset(); // Limpia variables de sesión
|
|
session_destroy(); // Destruye la sesión
|
|
|
|
header("Location: /IMPORTADORES/login");
|
|
exit;
|
|
}
|
|
|
|
function toggle_estado() {
|
|
session_start();
|
|
|
|
if (!($_SESSION['usuario_sistemas'] ?? false)) {
|
|
die("⚠️ No autorizado.");
|
|
}
|
|
|
|
$conn = getConnection();
|
|
|
|
$id = $_GET['id'] ?? null;
|
|
|
|
if (!$id || !is_numeric($id)) {
|
|
die("❌ ID inválido.");
|
|
}
|
|
|
|
// Obtener el estado actual
|
|
$sqlEstado = "SELECT activo FROM usuarios_sistema WHERE id_usuario = ?";
|
|
$stmtEstado = sqlsrv_query($conn, $sqlEstado, [$id]);
|
|
|
|
if (!$stmtEstado || !($row = sqlsrv_fetch_array($stmtEstado, SQLSRV_FETCH_ASSOC))) {
|
|
die("❌ Usuario no encontrado.");
|
|
}
|
|
|
|
$nuevoEstado = $row['activo'] ? 0 : 1;
|
|
|
|
// Actualizar estado
|
|
$sqlUpdate = "UPDATE usuarios_sistema SET activo = ? WHERE id_usuario = ?";
|
|
$stmtUpdate = sqlsrv_query($conn, $sqlUpdate, [$nuevoEstado, $id]);
|
|
|
|
if (!$stmtUpdate) {
|
|
die("❌ Error al actualizar: " . print_r(sqlsrv_errors(), true));
|
|
}
|
|
|
|
header("Location: /IMPORTADORES/sistemas/alta_usuarios");
|
|
exit;
|
|
}
|
|
|
|
|
|
|
|
function reset_password() {
|
|
session_start();
|
|
|
|
if (!($_SESSION['usuario_sistemas'] ?? false)) {
|
|
die("⚠️ No autorizado.");
|
|
}
|
|
|
|
$conn = getConnection();
|
|
|
|
$id = $_GET['id'] ?? null;
|
|
|
|
if (!$id || !is_numeric($id)) {
|
|
die("❌ ID inválido.");
|
|
}
|
|
|
|
// 🔐 Generar contraseña aleatoria de 10 caracteres
|
|
$randomPassword = bin2hex(random_bytes(5)); // genera algo como 'a8c4f1b92d'
|
|
$passwordHash = password_hash($randomPassword, PASSWORD_DEFAULT);
|
|
|
|
$sqlEmail = "SELECT email FROM usuarios_sistema WHERE id_usuario = ?";
|
|
$stmtEmail = sqlsrv_query($conn, $sqlEmail, [$id]);
|
|
$row = sqlsrv_fetch_array($stmtEmail, SQLSRV_FETCH_ASSOC);
|
|
|
|
|
|
|
|
|
|
$sql = "UPDATE usuarios_sistema SET password_hash = ? WHERE id_usuario = ?";
|
|
$stmt = sqlsrv_query($conn, $sql, [$passwordHash, $id]);
|
|
|
|
if (!$stmt) {
|
|
die("❌ Error al actualizar: " . print_r(sqlsrv_errors(), true));
|
|
}
|
|
|
|
// 🔁 Redirigir pasando la contraseña como parámetro temporal (solo visible para el admin)
|
|
header("Location: /IMPORTADORES/sistemas/alta_usuarios?reset=ok&pass=" . urlencode($randomPassword) . "&email=" . urlencode(decrypt($row['email'])));
|
|
|
|
exit;
|
|
}
|
|
|
|
|
|
|
|
function enviar_password() {
|
|
$email = $_GET['email'] ?? '';
|
|
$pass = $_GET['pass'] ?? '';
|
|
|
|
if (!$email || !$pass) {
|
|
http_response_code(400);
|
|
echo "Datos incompletos.";
|
|
return;
|
|
}
|
|
|
|
require_once __DIR__ . '/../../vendor/autoload.php';
|
|
|
|
$mail = new PHPMailer(true);
|
|
|
|
try {
|
|
$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->isHTML(true);
|
|
$mail->Subject = 'Nueva contraseña de acceso';
|
|
$mail->CharSet = 'UTF-8';
|
|
$logoURL='http://siih.aduanasoft.com/IMPORTADORES/public/assets/img/logo_siih.png';
|
|
$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;'>
|
|
<img src='$logoURL' alt='Logo $siglas' style='height: 80px; width: 80px; margin-bottom: 10px;'>
|
|
<h2 style='color: white;'>Contraseña restablecida</h2>
|
|
</div>
|
|
<div style='padding: 30px; color: #333; font-size: 16px;'>
|
|
<p>Tu contraseña de acceso al <strong>$nombreSistema</strong> ha sido restablecida por el administrador.</p>
|
|
<p style='margin-top: 20px; font-size: 18px;'>
|
|
<strong>Nueva contraseña:</strong><br>
|
|
<span style='background-color: #f0f0f0; padding: 10px 15px; border-radius: 5px; display: inline-block; font-family: monospace;'>$pass</span>
|
|
</p>
|
|
<p style='margin-top: 20px;'>Por favor, cambia esta contraseña una vez que inicies sesión.</p>
|
|
<hr style='margin: 30px 0;'>
|
|
<p style='font-size: 14px; color: #888;'>Este es un mensaje automático generado por el sistema. Si no solicitaste esta acción, contacta al administrador.</p>
|
|
</div>
|
|
<div style='background: #e9ecef; text-align: center; padding: 15px; font-size: 13px; color: #666;'>
|
|
© " . date('Y') . " $siglas · Desarrollado por AduanaSoft
|
|
</div>
|
|
</div>
|
|
</div>
|
|
";
|
|
|
|
$mail->send();
|
|
echo "Correo enviado";
|
|
} catch (Exception $e) {
|
|
http_response_code(500);
|
|
echo "Error al enviar correo: {$mail->ErrorInfo}";
|
|
}
|
|
}
|
|
|
|
|
|
|
|
function bitacora_login() {
|
|
if (!($_SESSION['usuario_sistemas'] ?? false)) {
|
|
die("⚠️ No autorizado.");
|
|
}
|
|
|
|
$conn = getConnection();
|
|
$sql = "SELECT * FROM bitacora_login ORDER BY fecha DESC";
|
|
$stmt = sqlsrv_query($conn, $sql);
|
|
|
|
$registros = [];
|
|
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
|
|
$registros[] = $row;
|
|
}
|
|
|
|
include __DIR__ . '/../../views/admin/bitacora_login.php';
|
|
}
|
|
|
|
function bitacora_usuarios() {
|
|
if (!($_SESSION['usuario_sistemas'] ?? false)) {
|
|
die("⚠️ No autorizado.");
|
|
}
|
|
|
|
$conn = getConnection();
|
|
$sql = "SELECT * FROM bitacora_usuarios ORDER BY fecha DESC";
|
|
$stmt = sqlsrv_query($conn, $sql);
|
|
|
|
$registros = [];
|
|
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
|
|
$registros[] = $row;
|
|
}
|
|
|
|
include __DIR__ . '/../../views/admin/bitacora_usuarios.php';
|
|
}
|