Files
zibo-dashboard/public/userarea/manutenzioni/ajax/auth_check.php
T
2026-08-12 21:29:55 +03:00

83 lines
2.3 KiB
PHP

<?php
/**
* Auth + permission guard for the Manutenzioni ajax endpoints.
* Include at the top of every handler; it defines $currentUserId.
*
* Authorisation is enforced here, on the backend — the UI only hides
* buttons, it never decides what a request is allowed to do.
*/
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
header('Content-Type: application/json; charset=utf-8');
if (empty($_SESSION['iduserlogin'])) {
http_response_code(401);
echo json_encode(['success' => false, 'message' => 'Non autorizzato. Effettua il login.']);
exit;
}
$currentUserId = (int)$_SESSION['iduserlogin'];
require_once __DIR__ . '/../include/functions.php';
if (!function_exists('mnt_user_can')) {
/**
* Permission check straight from the Vanguard RBAC tables
* (the Auth facade is not bootstrapped in these endpoints).
*/
function mnt_user_can(string $permission): bool
{
global $currentUserId;
static $permissions = null;
if ($permissions === null) {
$stmt = mnt_pdo()->prepare("
SELECT p.name
FROM auth_users u
INNER JOIN auth_permission_role pr ON pr.role_id = u.role_id
INNER JOIN auth_permissions p ON p.id = pr.permission_id
WHERE u.id = ?
");
$stmt->execute([$currentUserId]);
$permissions = $stmt->fetchAll(PDO::FETCH_COLUMN);
}
return in_array($permission, $permissions, true);
}
}
if (!function_exists('mnt_require_permission')) {
function mnt_require_permission(string $permission): void
{
if (!mnt_user_can($permission)) {
http_response_code(403);
echo json_encode(['success' => false, 'message' => 'Permesso negato.']);
exit;
}
}
}
if (!function_exists('mnt_json_fail')) {
function mnt_json_fail(string $message, int $code = 200): void
{
if ($code !== 200) {
http_response_code($code);
}
echo json_encode(['success' => false, 'message' => $message]);
exit;
}
}
if (!function_exists('mnt_json_ok')) {
function mnt_json_ok(array $payload = []): void
{
echo json_encode(['success' => true] + $payload);
exit;
}
}