src/Security/Voter/SwitchUserVoter.php line 10

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  4. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  5. use Symfony\Component\Security\Core\Security;
  6. use Symfony\Component\Security\Core\User\UserInterface;
  7. class SwitchUserVoter extends Voter
  8. {
  9.     /**
  10.      * SwitchUserVoter constructor.
  11.      */
  12.     public function __construct(
  13.         private Security $security
  14.     ) {
  15.     }
  16.     protected function supports(string $attributemixed $subject): bool
  17.     {
  18.         return 'CAN_SWITCH_USER' == $attribute && $subject instanceof UserInterface;
  19.     }
  20.     protected function voteOnAttribute(string $attributemixed $subjectTokenInterface $token): bool
  21.     {
  22.         $user $token->getUser();
  23.         if (!$user instanceof UserInterface || !$subject instanceof UserInterface) {
  24.             return false;
  25.         }
  26.         // you can still check for ROLE_ALLOWED_TO_SWITCH
  27.         if ($this->security->isGranted('ROLE_ALLOWED_TO_SWITCH')) {
  28.             if (!$this->security->isGranted('ROLE_SUPER_ADMIN') && in_array($subject->getRoles()[0], ['ROLE_ADMIN''ROLE_SUPER_ADMIN'])) {
  29.                 return false;
  30.             }
  31.             return true;
  32.         }
  33.         return false;
  34.     }
  35. }