52 lines
1.0 KiB
PHP
52 lines
1.0 KiB
PHP
<?php
|
|
session_start();
|
|
|
|
require_once 'db/config.php';
|
|
|
|
function is_logged_in() {
|
|
return isset($_SESSION['user_id']);
|
|
}
|
|
|
|
function require_login() {
|
|
if (!is_logged_in()) {
|
|
header('Location: login.php');
|
|
exit();
|
|
}
|
|
}
|
|
|
|
function current_user_role() {
|
|
if (!is_logged_in()) {
|
|
return null;
|
|
}
|
|
|
|
$pdo = db();
|
|
$stmt = $pdo->prepare('SELECT roles.name FROM users JOIN roles ON users.role_id = roles.id WHERE users.id = ?');
|
|
$stmt->execute([$_SESSION['user_id']]);
|
|
$role = $stmt->fetchColumn();
|
|
|
|
return $role;
|
|
}
|
|
|
|
function has_role($role_names) {
|
|
$current_role = current_user_role();
|
|
if (is_array($role_names)) {
|
|
return in_array($current_role, $role_names);
|
|
} else {
|
|
return $current_role === $role_names;
|
|
}
|
|
}
|
|
|
|
function require_role($role_names) {
|
|
require_login();
|
|
if (!has_role($role_names)) {
|
|
// http_response_code(403);
|
|
// echo 'Forbidden';
|
|
header('Location: index.php');
|
|
exit();
|
|
}
|
|
}
|
|
|
|
function isAdmin() {
|
|
return has_role('Admin');
|
|
}
|