<?php
// This file should be included after db.php and session_start()
/**
* Fetches all permission names for a given user and stores them in the session.
* Should be called once upon user login.
*
* @param int $user_id The user's ID.
* @param mysqli $conn The database connection object.
*/
function load_user_permissions($user_id, $conn) {
$permissions = [];
$sql = "SELECT p.name FROM permissions p
JOIN user_permissions up ON p.id = up.permission_id
WHERE up.user_id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
$permissions[] = $row['name'];
}
$_SESSION['permissions'] = $permissions;
$stmt->close();
}
/**
* Checks if the currently logged-in user has a specific permission.
*
* @param string $permission_name The name of the permission to check (e.g., 'cars_edit').
* @return bool True if the user has the permission, false otherwise.
*/
function has_permission($permission_name) {
// The super admin (user ID 1) always has all permissions.
if (isset($_SESSION['user_id']) && $_SESSION['user_id'] == 1) {
return true;
}
// Check if the permission exists in the user's session permissions array.
return isset($_SESSION['permissions']) && in_array($permission_name, $_SESSION['permissions']);
}
/**
* A helper function to protect a page.
* If the user doesn't have the required permission, it will stop script execution.
*
* @param string $permission_name The permission required to access the page.
*/
function require_permission($permission_name) {
if (!has_permission($permission_name)) {
// You can create a fancier "Access Denied" page if you want.
die("Access Denied. You do not have the required permission ($permission_name).");
}
}
?>