src/Security/ImpersonateUserVoter.php line 14

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