35512-vm/login.php
2025-11-08 20:43:02 +00:00

90 lines
3.1 KiB
PHP

<?php
session_start();
require_once 'db/config.php';
$error_message = '';
// If user is already logged in, redirect to dashboard
if (isset($_SESSION['user_id'])) {
header("Location: index.php");
exit;
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$email = $_POST['email'] ?? '';
$password = $_POST['password'] ?? '';
if (empty($email) || empty($password)) {
$error_message = 'Please enter both email and password.';
} else {
try {
$pdo = db();
$stmt = $pdo->prepare("SELECT u.*, r.name as role_name FROM users u JOIN roles r ON u.role_id = r.id WHERE u.email = ?");
$stmt->execute([$email]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if ($user && password_verify($password, $user['password'])) {
$_SESSION['user_id'] = $user['id'];
$_SESSION['user_name'] = $user['name'];
$_SESSION['user_role_id'] = $user['role_id'];
$_SESSION['user_role_name'] = $user['role_name'];
// For backwards compatibility with old code expecting a role name
$_SESSION['user_role'] = $user['role_name'];
header("Location: index.php");
exit;
} else {
$error_message = 'Invalid email or password.';
}
} catch (PDOException $e) {
$error_message = 'Database error: ' . $e->getMessage();
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login - IC-Inventory</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="assets/css/custom.css?v=<?php echo time(); ?>">
<style>
body {
display: flex;
align-items: center;
justify-content: center;
min-height: 100vh;
background-color: #f7f9fc;
}
.login-card {
max-width: 400px;
width: 100%;
}
</style>
</head>
<body>
<div class="card login-card shadow-sm">
<div class="card-body p-5">
<h1 class="card-title text-center mb-4">IC-Inventory</h1>
<?php if ($error_message): ?>
<div class="alert alert-danger"><?php echo htmlspecialchars($error_message); ?></div>
<?php endif; ?>
<form action="login.php" method="post">
<div class="mb-3">
<label for="email" class="form-label">Email address</label>
<input type="email" class="form-control" id="email" name="email" required>
</div>
<div class="mb-3">
<label for="password" class="form-label">Password</label>
<input type="password" class="form-control" id="password" name="password" required>
</div>
<button type="submit" class="btn btn-primary w-100">Login</button>
</form>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>