CheckPermission.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. namespace App\Http\Middleware;
  3. use App\Services\UserTypePermissionService;
  4. use Closure;
  5. use Illuminate\Http\Request;
  6. use Illuminate\Support\Facades\Auth;
  7. class CheckPermission
  8. {
  9. public function __construct(
  10. protected UserTypePermissionService $userTypePermissionService,
  11. ) {}
  12. /**
  13. * Handle an incoming request.
  14. *
  15. * @param string $scopes A string of scopes separated by '|' to check a single permission against.
  16. * @param string $permissionType The type of permission to check for each scope.
  17. * @return \Symfony\Component\HttpFoundation\Response
  18. */
  19. public function handle(Request $request, Closure $next, string $scopes, string $permissionType)
  20. {
  21. $user = Auth::user();
  22. $userPermissions = [];
  23. $userPermissions = $user
  24. ? $this->userTypePermissionService->allPermissionsByUserType($user->type)
  25. : $this->userTypePermissionService->allGuestPermissions();
  26. $hasPermission = false;
  27. foreach (explode(separator: '|', string: $scopes) as $scope) {
  28. if ($this->hasPermission(userPermissions: $userPermissions, scope: $scope, permissionType: $permissionType)) {
  29. $hasPermission = true;
  30. break;
  31. }
  32. }
  33. if (! $hasPermission) {
  34. return response()->json(data: ['message' => 'Unauthorized'], status: 403);
  35. }
  36. return $next($request);
  37. }
  38. private function hasPermission($userPermissions, string $scope, string $permissionType): bool
  39. {
  40. $bitwisePermissionTable = [
  41. 'view' => 1,
  42. 'add' => 2,
  43. 'edit' => 4,
  44. 'delete' => 8,
  45. 'print' => 16,
  46. 'export' => 32,
  47. 'import' => 64,
  48. 'limit' => 128,
  49. 'menu' => 256,
  50. ];
  51. $requiredPermission = $bitwisePermissionTable[$permissionType] ?? 0;
  52. $permissionRecord = $userPermissions->first(function ($permission) use ($scope) {
  53. return $permission->permission->scope === $scope;
  54. });
  55. if (! $permissionRecord) {
  56. return false;
  57. }
  58. return ($permissionRecord->bits & $requiredPermission) === $requiredPermission;
  59. }
  60. }