src/Bundles/UserBundle/Security/Voter/RolePermissionsVoter.php line 18

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Bundles\UserBundle\Security\Voter;
  4. use App\Bundles\OrganizationBundle\Exception\UserOrganizationNotFoundException;
  5. use App\Bundles\OrganizationBundle\Service\UserOrganization\UserOrganizationBinder;
  6. use App\Bundles\OrganizationBundle\Service\UserOrganization\UserOrganizationProvider;
  7. use App\Bundles\UserBundle\Entity\Permission;
  8. use App\Bundles\UserBundle\Enum\RolePermissionEnum;
  9. use App\Bundles\UserBundle\Repository\PermissionRepository;
  10. use App\Platform\Service\SessionProvider;
  11. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  12. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  13. use Throwable;
  14. class RolePermissionsVoter extends Voter
  15. {
  16.     public function __construct(
  17.         private readonly PermissionRepository $permissionRepository,
  18.         private readonly SessionProvider $sessionProvider,
  19.         private readonly UserOrganizationBinder $organizationBinder,
  20.         private readonly UserOrganizationProvider $provider,
  21.     ) {
  22.     }
  23.     protected function supports(string $attribute$subject): bool
  24.     {
  25.         return (bool)RolePermissionEnum::tryFrom($attribute);
  26.     }
  27.     /**
  28.      * @throws UserOrganizationNotFoundException
  29.      */
  30.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token): bool
  31.     {
  32.         if (!$token->getUser()) {
  33.             return false;
  34.         }
  35.         try {
  36.             $session $this->sessionProvider->provide();
  37.         } catch (Throwable) {
  38.             return false;
  39.         }
  40.         if (!$session->has($this->organizationBinder::SESSION_USER_ORGANIZATION_KEY)) {
  41.             return false;
  42.         }
  43.         $userOrganization $this->provider->provide(
  44.             $session->get($this->organizationBinder::SESSION_USER_ORGANIZATION_KEY)
  45.         );
  46.         $userPermissions $this->permissionRepository->findForUserInOrganization(
  47.             $userOrganization->getOrganization(),
  48.             $token->getUser()
  49.         );
  50.         $permissionNames array_map(fn(Permission $permission) => $permission->getValue(), $userPermissions);
  51.         return in_array($attribute$permissionNames);
  52.     }
  53. }