userTypePermissionService->allGuestPermissions()); } else { $userPermissions = UserTypePermissionResource::collection(resource: $this->userTypePermissionService->allPermissionsByUserType(userType: $user->type)); } // Check the required permission for each scope $hasPermission = false; foreach (explode(separator: '|', string: $scopes) as $scope) { if ($this->hasPermission(userPermissions: $userPermissions, scope: $scope, permissionType: $permissionType)) { $hasPermission = true; break; } } if (!$hasPermission) { return response()->json(data: ['message' => 'Unauthorized'], status: 403); } return $next($request); } private function hasPermission($userPermissions, string $scope, string $permissionType): bool { $bitwisePermissionTable = [ 'view' => 1, 'add' => 2, 'edit' => 4, 'delete' => 8, 'print' => 16, 'export' => 32, 'import' => 64, 'limit' => 128, 'menu' => 256, ]; $requiredPermission = $bitwisePermissionTable[$permissionType] ?? 0; foreach ($userPermissions as $permission) { if ($permission['scope'] === $scope && ($permission['bits'] & $requiredPermission)) { return true; } } return false; } }