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

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. class RolePermissionsVoter extends Voter
  14. {
  15.     public function __construct(
  16.         private readonly PermissionRepository $permissionRepository,
  17.         private readonly SessionProvider $sessionProvider,
  18.         private readonly UserOrganizationBinder $organizationBinder,
  19.         private readonly UserOrganizationProvider $provider,
  20.     ) {
  21.     }
  22.     protected function supports(string $attribute$subject): bool
  23.     {
  24.         return (bool)RolePermissionEnum::tryFrom($attribute);
  25.     }
  26.     /**
  27.      * @throws UserOrganizationNotFoundException
  28.      */
  29.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token): bool
  30.     {
  31.         if (!$token->getUser()) {
  32.             return false;
  33.         }
  34.         // TODO: get organization from session
  35.         $session $this->sessionProvider->provide();
  36.         if (!$session->has($this->organizationBinder::SESSION_USER_ORGANIZATION_KEY)) {
  37.             return false;
  38.         }
  39.         $userOrganization $this->provider->provide(
  40.             $session->get($this->organizationBinder::SESSION_USER_ORGANIZATION_KEY)
  41.         );
  42.         $userPermissions $this->permissionRepository->findForUserInOrganization(
  43.             $userOrganization->getOrganization(),
  44.             $token->getUser()
  45.         );
  46.         $permissionNames array_map(fn(Permission $permission) => $permission->getValue(), $userPermissions);
  47.         return in_array($attribute$permissionNames);
  48.     }
  49. }