48 lines
1.4 KiB
PHP
48 lines
1.4 KiB
PHP
<?php
|
|
session_start();
|
|
require_once __DIR__ . '/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_message'] = 'Please enter both username and password.';
|
|
header('Location: login.php');
|
|
exit();
|
|
}
|
|
|
|
try {
|
|
$pdo = db();
|
|
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
|
|
$stmt->execute([':username' => $username]);
|
|
$user = $stmt->fetch(PDO::FETCH_ASSOC);
|
|
|
|
if ($user && password_verify($password, $user['password'])) {
|
|
// Password is correct, start session
|
|
session_regenerate_id(); // Prevents session fixation
|
|
$_SESSION['user_id'] = $user['id'];
|
|
$_SESSION['username'] = $user['username'];
|
|
$_SESSION['role'] = $user['role'];
|
|
$_SESSION['full_name'] = $user['full_name'];
|
|
$_SESSION['department'] = $user['department'];
|
|
|
|
header("Location: index.php");
|
|
exit();
|
|
} else {
|
|
$_SESSION['error_message'] = 'Invalid username or password.';
|
|
header("Location: login.php");
|
|
exit();
|
|
}
|
|
} catch (PDOException $e) {
|
|
// In a real app, you'd log this error
|
|
// error_log("Login error: " . $e->getMessage());
|
|
$_SESSION['error_message'] = 'A database error occurred. Please try again later.';
|
|
header('Location: login.php');
|
|
exit();
|
|
}
|