94 lines
3.2 KiB
PHP
94 lines
3.2 KiB
PHP
<?php
|
|
session_start();
|
|
require_once 'db/config.php';
|
|
|
|
// If already logged in, redirect to the appropriate page
|
|
if (isset($_SESSION['user_id'])) {
|
|
if (in_array('Admin', $_SESSION['user_roles'])) {
|
|
header('Location: admin.php');
|
|
} else {
|
|
header('Location: index.php');
|
|
}
|
|
exit;
|
|
}
|
|
|
|
$pageTitle = "Login";
|
|
require_once 'templates/header.php';
|
|
|
|
$error = '';
|
|
|
|
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
|
$username = trim($_POST['username']);
|
|
$password = $_POST['password'];
|
|
|
|
if (empty($username) || empty($password)) {
|
|
$error = 'Please fill out all fields.';
|
|
} else {
|
|
$pdo = db();
|
|
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
|
|
$stmt->execute([$username]);
|
|
$user = $stmt->fetch();
|
|
|
|
if ($user && password_verify($password, $user['password'])) {
|
|
// Get user roles
|
|
$roles_stmt = $pdo->prepare("SELECT r.role_name FROM user_roles ur JOIN roles r ON ur.role_id = r.id WHERE ur.user_id = ?");
|
|
$roles_stmt->execute([$user['id']]);
|
|
$roles = $roles_stmt->fetchAll(PDO::FETCH_COLUMN);
|
|
|
|
// Store user info in session
|
|
$_SESSION['user_id'] = $user['id'];
|
|
$_SESSION['username'] = $user['username'];
|
|
$_SESSION['email'] = $user['email'];
|
|
$_SESSION['user_roles'] = $roles;
|
|
|
|
// Redirect based on role
|
|
if (in_array('Admin', $roles)) {
|
|
header('Location: admin.php');
|
|
} else {
|
|
header('Location: index.php');
|
|
}
|
|
exit;
|
|
} else {
|
|
$error = 'Invalid username or password.';
|
|
}
|
|
}
|
|
}
|
|
?>
|
|
|
|
<main>
|
|
<section class="survey-section">
|
|
<div class="container">
|
|
<div class="row justify-content-center">
|
|
<div class="col-md-6">
|
|
<div class="card">
|
|
<div class="card-body">
|
|
<h1 class="card-title text-center">Login</h1>
|
|
<?php if ($error):
|
|
?>
|
|
<div class="alert alert-danger"><?= $error ?></div>
|
|
<?php endif;
|
|
?>
|
|
<form method="POST">
|
|
<div class="form-group">
|
|
<label for="username" class="form-label">Username</label>
|
|
<input type="text" id="username" name="username" class="form-control" required>
|
|
</div>
|
|
<div class="form-group">
|
|
<label for="password" class="form-label">Password</label>
|
|
<input type="password" id="password" name="password" class="form-control" required>
|
|
</div>
|
|
<button type="submit" class="btn btn-primary btn-block">Login</button>
|
|
</form>
|
|
<p class="mt-3 text-center">Don't have an account? <a href="register.php">Register here</a>.</p>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</section>
|
|
</main>
|
|
|
|
<?php
|
|
require_once 'templates/footer.php';
|
|
?>
|