34786-vm/auth/handle_login.php
2025-12-12 16:33:10 +00:00

50 lines
1.4 KiB
PHP

<?php
session_start();
require_once __DIR__ . '/../db/config.php';
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
header('Location: /auth/login.php');
exit();
}
$email = $_POST['email'] ?? '';
$password = $_POST['password'] ?? '';
if (empty($email) || empty($password)) {
$_SESSION['login_error'] = 'Por favor, ingresa tu correo y contraseña.';
header('Location: /auth/login.php');
exit();
}
try {
$pdo = db();
$stmt = $pdo->prepare("SELECT * FROM usuarios WHERE email = :email");
$stmt->execute(['email' => $email]);
$user = $stmt->fetch();
if ($user && password_verify($password, $user['password'])) {
// Login exitoso
session_regenerate_id(true);
$_SESSION['user_id'] = $user['id'];
$_SESSION['user_nombre'] = $user['nombre'];
$_SESSION['user_rol'] = $user['rol'];
// Redirigir al dashboard
header('Location: /index.php');
exit();
} else {
// Error de credenciales
$_SESSION['login_error'] = 'El correo o la contraseña son incorrectos.';
header('Location: /auth/login.php');
exit();
}
} catch (PDOException $e) {
// Error de base de datos
// En un entorno de producción, esto debería ser registrado en un log.
$_SESSION['login_error'] = 'Ocurrió un error en el servidor. Inténtalo de nuevo más tarde.';
// die($e->getMessage()); // Para depuración
header('Location: /auth/login.php');
exit();
}