34802-vm/auth.php
2025-10-08 14:10:03 +00:00

55 lines
1.6 KiB
PHP

<?php
session_start();
require_once 'db/config.php';
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
header('Location: login.php');
exit;
}
$username = $_POST['username'] ?? '';
$password = $_POST['password'] ?? '';
if (empty($username) || empty($password)) {
$_SESSION['error'] = 'Por favor, complete todos los campos.';
header('Location: login.php');
exit;
}
try {
$pdo = db();
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->bindParam(':username', $username);
$stmt->execute();
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if ($user && password_verify($password, $user['password'])) {
// Regenerate session ID to prevent session fixation
session_regenerate_id(true);
// Store user data in session
$_SESSION['user_id'] = $user['id'];
$_SESSION['username'] = $user['username'];
$_SESSION['role'] = $user['role'];
// Redirect based on role
if ($user['role'] === 'admin') {
header('Location: dashboard.php');
} else {
// Redirect to a general user page or index if not admin
header('Location: index.php');
}
exit;
} else {
$_SESSION['error'] = 'Usuario o contraseña incorrectos.';
header('Location: login.php');
exit;
}
} catch (PDOException $e) {
// In a real app, log this error instead of showing it to the user
$_SESSION['error'] = 'Error de base de datos. Intente de nuevo más tarde.';
// error_log($e->getMessage());
header('Location: login.php');
exit;
}