src/Security/Voter/B2bCustomerUserVoter.php line 11

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\Customer;
  4. use App\Entity\User;
  5. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  6. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  7. /** Authorization rules used only by the B2B customer user management page. */
  8. class B2bCustomerUserVoter extends Voter
  9. {
  10.     public const MANAGE = 'B2B_CUSTOMER_USER_MANAGE';
  11.     public const MANAGE_MODULES = 'B2B_CUSTOMER_USER_MANAGE_MODULES';
  12.     protected function supports(string $attribute, mixed $subject): bool
  13.     {
  14.         return match ($attribute) {
  15.             self::MANAGE => $subject instanceof Customer || $subject instanceof User,
  16.             self::MANAGE_MODULES => $subject instanceof User,
  17.             default => false,
  18.         };
  19.     }
  20.     protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool
  21.     {
  22.         $currentUser = $token->getUser();
  23.         if (!$currentUser instanceof User) {
  24.             return false;
  25.         }
  26.         $roles = $token->getRoleNames();
  27.         if (in_array('ROLE_ADMIN', $roles, true)) {
  28.             return $attribute !== self::MANAGE_MODULES
  29.                 || $subject->getId() !== $currentUser->getId();
  30.         }
  31.         if (!in_array('ROLE_B2B_ADMIN', $roles, true)) {
  32.             return false;
  33.         }
  34.         $targetCustomer = $subject instanceof Customer ? $subject : $subject->getCustomer();
  35.         $currentCustomer = $currentUser->getCustomer();
  36.         if ($targetCustomer === null || $currentCustomer === null
  37.             || $targetCustomer->getId() !== $currentCustomer->getId()
  38.         ) {
  39.             return false;
  40.         }
  41.         if ($attribute === self::MANAGE_MODULES
  42.             && !in_array('ROLE_B2B_AGENT', $subject->getRoles(), true)
  43.         ) {
  44.             return false;
  45.         }
  46.         return $attribute !== self::MANAGE_MODULES
  47.             || $subject->getId() !== $currentUser->getId();
  48.     }
  49. }