<?php
require_once __DIR__ . '/functions.php';
if (session_status() !== PHP_SESSION_ACTIVE) {
session_start();
}
/** Redirect to login if not authenticated. Call at the top of every protected admin page. */
function require_login(): void {
if (empty($_SESSION['admin_user_id'])) {
redirect('login.php');
}
}
/** Restrict a page to specific roles, e.g. require_role(['admin']). */
function require_role(array $roles): void {
require_login();
if (!in_array($_SESSION['admin_role'] ?? '', $roles, true)) {
http_response_code(403);
die('You do not have permission to access this page.');
}
}
function current_user(): ?array {
if (empty($_SESSION['admin_user_id'])) return null;
static $user = null;
if ($user === null) {
$stmt = db()->prepare('SELECT id, name, username, email, role, avatar FROM users WHERE id = ?');
$stmt->execute([$_SESSION['admin_user_id']]);
$user = $stmt->fetch() ?: null;
}
return $user;
}
function attempt_login(string $username, string $password): bool {
$stmt = db()->prepare('SELECT * FROM users WHERE (username = ? OR email = ?) AND status = "active" LIMIT 1');
$stmt->execute([$username, $username]);
$user = $stmt->fetch();
if ($user && password_verify($password, $user['password_hash'])) {
session_regenerate_id(true);
$_SESSION['admin_user_id'] = $user['id'];
$_SESSION['admin_role'] = $user['role'];
$_SESSION['admin_name'] = $user['name'];
$upd = db()->prepare('UPDATE users SET last_login = NOW() WHERE id = ?');
$upd->execute([$user['id']]);
return true;
}
return false;
}
function logout(): void {
$_SESSION = [];
if (ini_get('session.use_cookies')) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000, $params['path'], $params['domain'], $params['secure'], $params['httponly']);
}
session_destroy();
}