expectsJson($request)) { return new JsonResponse([ 'error' => 'Não autorizado', 'message' => 'Você precisa estar autenticado para acessar esta página.' ], 401); } return new Response('', 302, [ 'Location' => url('/login') ]); } // Check if the user has admin permissions $user = User::find($_SESSION['user_id']); if (!$user || !$this->isAdmin($user)) { if ($this->expectsJson($request)) { return new JsonResponse([ 'error' => 'Acesso negado', 'message' => 'Você não tem permissão para acessar esta página.' ], 403); } return new Response('', 302, [ 'Location' => url('/') ]); } return $next($request); } /** * Check if the request expects JSON. * * @param Request $request * @return bool */ private function expectsJson(Request $request): bool { return $request->isXmlHttpRequest() || strpos($request->headers->get('Accept'), 'application/json') !== false; } /** * Checks if the user has admin permissions. * * @param User $user * @return bool */ private function isAdmin(User $user): bool { // Check if the user has the admin role if (method_exists($user, 'hasRole') && $user->hasRole('admin')) { return true; } // Check if the user has the admin.access permission if (method_exists($user, 'hasPermission') && $user->hasPermission('admin.access')) { return true; } // Check if the is_admin field exists and is true if (isset($user->is_admin) && $user->is_admin) { return true; } // Check if the level field exists and is greater than or equal to 5 if (isset($user->level) && $user->level >= 5) { return true; } return false; } }