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\Service\SecurityService;
  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.     private SecurityService $securityService;
  14.     public function __construct(
  15.         ParameterBagInterface $parameterBag,
  16.         SecurityService $securityService
  17.     ) {
  18.         $this->parameterBag $parameterBag;
  19.         $this->securityService $securityService;
  20.     }
  21.     public const CAN_SWITCH_USER 'CAN_SWITCH_USER';
  22.     protected function supports($attribute$subject): bool
  23.     {
  24.         return $attribute === self::CAN_SWITCH_USER && $subject instanceof Customer;
  25.     }
  26.     protected function voteOnAttribute($attribute$subjectTokenInterface $token): bool
  27.     {
  28.         $user $token->getUser();
  29.         if (!$user instanceof Employee || !$subject instanceof Customer) {
  30.             return false;
  31.         }
  32.         if ($this->requestedUserIsEmployee($subject->getEmail())) {
  33.             return $user->getEmail() === $subject->getEmail();
  34.         }
  35.         return $this->securityService->isGranted(AdminAclVoter::ALLOW_ADMIN_ACCESS'customer_admin_impersonate');
  36.     }
  37.     protected function requestedUserIsEmployee(string $email): bool
  38.     {
  39.         return str_contains($email$this->parameterBag->get('microsoft_tenant_email_postfix'));
  40.     }
  41. }