Files
whatsapp/diagnostico_login_avanzado.php
T
2026-01-12 11:06:43 -05:00

301 lines
12 KiB
PHP

<?php
/**
* Herramienta de Diagnóstico de Login - Versión Mejorada
* WhatsApp Bot Manager
* Fecha: 4 de enero de 2026
*/
require_once 'config/config.php';
// Solo permitir acceso desde localhost por seguridad
$allowedIPs = ['127.0.0.1', '::1', 'localhost'];
$clientIP = $_SERVER['REMOTE_ADDR'] ?? $_SERVER['HTTP_X_FORWARDED_FOR'] ?? 'unknown';
if (!in_array($clientIP, $allowedIPs) && $clientIP !== 'unknown') {
die("❌ Acceso denegado. Esta utilidad solo puede ejecutarse desde localhost por seguridad.");
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>🔍 Diagnóstico de Login Avanzado - WhatsApp Bot Manager</title>
<style>
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: linear-gradient(135deg, #25D366 0%, #128C7E 100%);
color: #333;
margin: 0;
padding: 20px;
min-height: 100vh;
}
.container {
max-width: 1000px;
margin: 0 auto;
background: white;
padding: 40px;
border-radius: 15px;
box-shadow: 0 10px 30px rgba(0,0,0,0.2);
}
h1 {
color: #25D366;
text-align: center;
margin-bottom: 30px;
}
.info-box {
background: #e8f5e8;
padding: 20px;
border-left: 5px solid #25D366;
margin: 20px 0;
border-radius: 5px;
}
.warning-box {
background: #fff3cd;
padding: 20px;
border-left: 5px solid #ffc107;
margin: 20px 0;
border-radius: 5px;
}
.error-box {
background: #f8d7da;
padding: 20px;
border-left: 5px solid #dc3545;
margin: 20px 0;
border-radius: 5px;
}
.form-group {
margin: 20px 0;
}
label {
display: block;
font-weight: bold;
margin-bottom: 8px;
color: #333;
}
input[type="password"], input[type="text"] {
width: 100%;
padding: 12px;
border: 2px solid #ddd;
border-radius: 8px;
font-size: 16px;
box-sizing: border-box;
}
input:focus {
outline: none;
border-color: #25D366;
}
.btn {
background: #25D366;
color: white;
padding: 12px 30px;
border: none;
border-radius: 8px;
font-size: 16px;
cursor: pointer;
margin: 10px 5px;
}
.btn:hover {
background: #1aa347;
}
.diagnostic-result {
background: #f8f9fa;
padding: 20px;
border-radius: 8px;
margin: 20px 0;
font-family: monospace;
border: 1px solid #dee2e6;
}
.admin-table {
width: 100%;
border-collapse: collapse;
margin: 20px 0;
}
.admin-table th, .admin-table td {
border: 1px solid #ddd;
padding: 12px;
text-align: left;
}
.admin-table th {
background: #25D366;
color: white;
}
.admin-table tr:nth-child(even) {
background: #f8f9fa;
}
.status-active {
color: #28a745;
font-weight: bold;
}
.status-inactive {
color: #dc3545;
font-weight: bold;
}
</style>
</head>
<body>
<div class="container">
<h1>🔍 Diagnóstico de Login Avanzado</h1>
<?php
try {
$pdo = createDbConnection();
echo '<div class="info-box">';
echo '<h4>✅ Conexión a Base de Datos: EXITOSA</h4>';
echo '</div>';
// Verificar estado del sistema
$isMigrated = isAuthSystemMigrated();
echo '<div class="info-box">';
echo '<h4>📊 Estado del Sistema de Autenticación</h4>';
echo '<p><strong>Sistema migrado a BD:</strong> ' . ($isMigrated ? '✅ SÍ' : '❌ NO - Sistema Legacy') . '</p>';
if ($isMigrated) {
echo '<p><strong>Tabla admin_users:</strong> ✅ Existe</p>';
// Contar administradores
$stmt = $pdo->query("SELECT COUNT(*) as total, COUNT(CASE WHEN is_active = 1 THEN 1 END) as active FROM admin_users");
$counts = $stmt->fetch();
echo '<p><strong>Total administradores:</strong> ' . $counts['total'] . '</p>';
echo '<p><strong>Administradores activos:</strong> ' . $counts['active'] . '</p>';
} else {
echo '<p><strong>Usuario por defecto:</strong> admin (sistema hardcodeado)</p>';
}
echo '</div>';
// Mostrar lista de administradores si existe la tabla
if ($isMigrated) {
echo '<h3>👥 Lista de Administradores en Base de Datos</h3>';
$stmt = $pdo->query("SELECT * FROM admin_users ORDER BY created_at DESC");
$admins = $stmt->fetchAll();
if (empty($admins)) {
echo '<div class="warning-box">⚠️ No hay administradores en la base de datos</div>';
} else {
echo '<table class="admin-table">';
echo '<tr><th>ID</th><th>Usuario</th><th>Nombre</th><th>Email</th><th>Estado</th><th>Creado</th><th>Último Login</th></tr>';
foreach ($admins as $admin) {
echo '<tr>';
echo '<td>' . $admin['id'] . '</td>';
echo '<td><strong>' . htmlspecialchars($admin['username']) . '</strong></td>';
echo '<td>' . htmlspecialchars($admin['full_name'] ?? 'Sin nombre') . '</td>';
echo '<td>' . htmlspecialchars($admin['email'] ?? 'Sin email') . '</td>';
echo '<td><span class="status-' . ($admin['is_active'] ? 'active">✅ Activo' : 'inactive">❌ Inactivo') . '</span></td>';
echo '<td>' . ($admin['created_at'] ?? 'No disponible') . '</td>';
echo '<td>' . ($admin['last_login'] ?? 'Nunca') . '</td>';
echo '</tr>';
}
echo '</table>';
}
}
// Procesar test de login
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['test_user'])) {
$testUsername = trim($_POST['username']);
$testPassword = $_POST['password'];
echo '<div class="diagnostic-result">';
echo '<h4>🔍 Resultado del Diagnóstico de Login</h4>';
echo '<strong>Usuario probado:</strong> ' . htmlspecialchars($testUsername) . '<br>';
echo '<strong>Fecha/Hora:</strong> ' . date('Y-m-d H:i:s') . '<br><br>';
// Probar autenticación
$authResult = authenticateUser($testUsername, $testPassword);
if ($authResult) {
echo '<div style="color: green; font-weight: bold;">✅ LOGIN EXITOSO</div><br>';
echo '<strong>Datos del usuario autenticado:</strong><br>';
echo '- ID: ' . $authResult['id'] . '<br>';
echo '- Usuario: ' . htmlspecialchars($authResult['username']) . '<br>';
echo '- Nombre: ' . htmlspecialchars($authResult['full_name']) . '<br>';
echo '- Email: ' . htmlspecialchars($authResult['email']) . '<br>';
} else {
echo '<div style="color: red; font-weight: bold;">❌ LOGIN FALLIDO</div><br>';
// Diagnóstico detallado
if ($isMigrated) {
$stmt = $pdo->prepare("SELECT * FROM admin_users WHERE username = ?");
$stmt->execute([$testUsername]);
$user = $stmt->fetch();
if (!$user) {
echo '<strong>Razón:</strong> Usuario "' . htmlspecialchars($testUsername) . '" no existe en BD<br>';
} elseif (!$user['is_active']) {
echo '<strong>Razón:</strong> Usuario existe pero está INACTIVO<br>';
} else {
echo '<strong>Razón:</strong> Usuario existe y está activo, pero la contraseña es incorrecta<br>';
// Mostrar información del usuario encontrado
echo '<br><strong>Información del usuario en BD:</strong><br>';
echo '- ID: ' . $user['id'] . '<br>';
echo '- Usuario: ' . htmlspecialchars($user['username']) . '<br>';
echo '- Nombre: ' . htmlspecialchars($user['full_name'] ?? 'Sin nombre') . '<br>';
echo '- Activo: ' . ($user['is_active'] ? 'Sí' : 'No') . '<br>';
echo '- Hash de contraseña: ' . substr($user['password_hash'], 0, 20) . '...<br>';
}
} else {
if ($testUsername !== 'admin') {
echo '<strong>Razón:</strong> Sistema legacy - solo acepta usuario "admin"<br>';
} else {
echo '<strong>Razón:</strong> Usuario correcto pero contraseña incorrecta<br>';
echo '<strong>Sistema:</strong> Legacy (hardcodeado)<br>';
echo '<strong>Hash esperado:</strong> ' . substr(ADMIN_PASSWORD, 0, 20) . '...<br>';
}
}
}
echo '</div>';
}
} catch (Exception $e) {
echo '<div class="error-box">';
echo '<h4>❌ Error de Sistema</h4>';
echo '<p>Error: ' . htmlspecialchars($e->getMessage()) . '</p>';
echo '</div>';
}
?>
<h3>🧪 Probar Credenciales de Login</h3>
<form method="post">
<div class="form-group">
<label for="username">Usuario:</label>
<input type="text" id="username" name="username" required
value="<?php echo htmlspecialchars($_POST['username'] ?? ''); ?>"
placeholder="Ingresa el nombre de usuario">
</div>
<div class="form-group">
<label for="password">Contraseña:</label>
<input type="password" id="password" name="password" required
placeholder="Ingresa la contraseña">
</div>
<input type="hidden" name="test_user" value="1">
<button type="submit" class="btn">🔍 Probar Autenticación</button>
</form>
<div class="info-box" style="margin-top: 30px;">
<h4>🌐 Enlaces del Sistema:</h4>
<p><strong>Login oficial:</strong> <a href="login.php" target="_blank">login.php</a></p>
<p><strong>Panel principal:</strong> <a href="index.php" target="_blank">index.php</a></p>
<p><strong>Gestión de admins:</strong> <a href="gestion_admin_unificada.php" target="_blank">gestion_admin_unificada.php</a></p>
<p><strong>Migración a BD:</strong> <a href="migrate_to_database_auth.php" target="_blank">migrate_to_database_auth.php</a></p>
</div>
<div class="warning-box" style="margin-top: 30px;">
<h4>⚠️ Notas de Seguridad:</h4>
<ul>
<li>Esta herramienta solo funciona desde localhost por seguridad</li>
<li>Elimínala en producción</li>
<li>Los errores de autenticación se registran en logs del sistema</li>
<li>Si el sistema está migrado, solo usuarios en la tabla admin_users pueden loguearse</li>
</ul>
</div>
</div>
</body>
</html>