CheckPermission.php 2.5 KB

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