src/Security/ImpersonateUserVoter.php line 15

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Security;
  4. use App\Entity\System\Customer;
  5. use App\Entity\System\Employee;
  6. use App\Entity\System\Role;
  7. use App\Service\SecurityService;
  8. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  9. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  10. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  11. class ImpersonateUserVoter extends Voter
  12. {
  13.     private ParameterBagInterface $parameterBag;
  14.     private SecurityService $securityService;
  15.     public function __construct(
  16.         ParameterBagInterface $parameterBag,
  17.         SecurityService $securityService
  18.     ) {
  19.         $this->parameterBag $parameterBag;
  20.         $this->securityService $securityService;
  21.     }
  22.     public const CAN_SWITCH_USER 'CAN_SWITCH_USER';
  23.     protected function supports($attribute$subject): bool
  24.     {
  25.         return $attribute === self::CAN_SWITCH_USER && $subject instanceof Customer;
  26.     }
  27.     protected function voteOnAttribute($attribute$subjectTokenInterface $token): bool
  28.     {
  29.         $user $token->getUser();
  30.         if (!$user instanceof Employee || !$subject instanceof Customer) {
  31.             return false;
  32.         }
  33.         if ($this->loggedUserIsAdmin($user)) {
  34.             return true;
  35.         }
  36.         if ($this->requestedUserIsEmployee($subject->getEmail())) {
  37.             return $user->getEmail() === $subject->getEmail();
  38.         }
  39.         $userRolesIndex = \array_flip($user->getRoles());
  40.         return $this->loggedUserHasAnyImpersonatorRole($userRolesIndex);
  41.     }
  42.     protected function requestedUserIsEmployee(string $email): bool
  43.     {
  44.         return str_contains($email$this->parameterBag->get('microsoft_tenant_email_postfix'));
  45.     }
  46.     protected function loggedUserIsAdmin(Employee $user): bool
  47.     {
  48.         return $this->securityService->isGranted(Role::ROLE_EMPLOYEE_DEVELOPER);
  49.     }
  50.     /**
  51.      * @param array<string, array-key> $userRolesIndex
  52.      */
  53.     public function loggedUserHasAnyImpersonatorRole(array $userRolesIndex): bool
  54.     {
  55.         return \array_key_exists(Role::ROLE_EMPLOYEE_SUPER_ADMIN$userRolesIndex)
  56.             || \array_key_exists(Role::ROLE_EMPLOYEE_TECH_SUPPORT$userRolesIndex)
  57.             || \array_key_exists(Role::ROLE_EMPLOYEE_SALES_ADMIN$userRolesIndex)
  58.             || \array_key_exists('ROLE_FINANCE'$userRolesIndex);
  59.     }
  60. }