CheckPermission.php 2.4 KB

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