Files
2025-09-28 16:05:53 +02:00

92 lines
2.7 KiB
PHP

<?php
require_once __DIR__ . '/init.php';
// Determine which page is being accessed
$current_page = basename($_SERVER['PHP_SELF']);
// These pages always require authentication
$protected_pages = ['bookmarks.php', 'settings.php', 'api/pexels.php', 'api/update_order.php'];
// Assume authentication is not required by default
$auth_required = false;
// Check if the current page must be protected
if (in_array($current_page, $protected_pages)) {
$auth_required = true;
} else if ($current_page === 'index.php') {
// index.php is only protected if the setting is enabled
try {
$stmt = $pdo->query("SELECT value FROM settings WHERE key = 'dashboard_protected'");
$dashboard_protected = $stmt->fetchColumn();
if ($dashboard_protected === '1') {
$auth_required = true;
}
} catch (Exception $e) {
// If the setting can't be read, default to requiring authentication for safety
$auth_required = true;
}
}
// If authentication is required for the page, check for a valid session
if ($auth_required && !isset($_SESSION['user_id']) && !isset($_SESSION['guest_tab_id'])) {
// For API calls, return a JSON error instead of redirecting
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
header('Content-Type: application/json');
http_response_code(401);
echo json_encode(['error' => 'Authentication required.']);
exit;
}
// For regular pages, redirect to login
header('Location: /login.php');
exit;
}
// --- Role-based Access Control (RBAC) Helper Functions ---
/**
* Checks if the current logged-in user is an admin.
* @return bool
*/
function isAdmin() {
return isset($_SESSION['role']) && $_SESSION['role'] === 'admin';
}
/**
* Checks if the current logged-in user is a standard user.
* @return bool
*/
function isUser() {
return isset($_SESSION['role']) && $_SESSION['role'] === 'user';
}
/**
* Checks if the current logged-in user is a viewer.
* @return bool
*/
function isViewer() {
return isset($_SESSION['role']) && $_SESSION['role'] === 'viewer';
}
/**
* Checks if the current user can edit a specific tab.
* Admins can edit any tab.
* Users can only edit tabs they own.
* @param int $tab_id The ID of the tab to check.
* @return bool
*/
function canEditTab($tab_id) {
if (isAdmin()) {
return true;
}
if (isUser()) {
global $pdo;
$stmt = $pdo->prepare("SELECT id FROM tabs WHERE id = ? AND user_id = ?");
$stmt->execute([$tab_id, $_SESSION['user_id']]);
if ($stmt->fetch()) {
return true;
}
}
return false;
}