| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 |
- <?php
- namespace App\Http\Middleware;
- use App\Http\Resources\UserTypePermissionResource;
- use Closure;
- use Illuminate\Http\Request;
- use Illuminate\Support\Facades\Auth;
- use App\Services\UserTypePermissionService;
- class CheckPermission
- {
- public function __construct(
- protected UserTypePermissionService $userTypePermissionService,
- ) {}
- /**
- * Handle an incoming request.
- *
- * @param \Illuminate\Http\Request $request
- * @param \Closure $next
- * @param string $scopes A string of scopes separated by '|' to check a single permission against.
- * @param string $permissionType The type of permission to check for each scope.
- * @return \Symfony\Component\HttpFoundation\Response
- */
- public function handle(Request $request, Closure $next, string $scopes, string $permissionType)
- {
- $user = Auth::user();
- // Get permissions for the user or guest
- if (!$user) {
- $userPermissions = UserTypePermissionResource::collection(resource: $this->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;
- }
- }
|