src/Security/Voter/SwitchtoUserVoter.php line 9

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 SwitchtoUserVoter extends Voter
  8. {
  9.     private $security;
  10.     public function __construct(Security $security)
  11.     {
  12.         $this->security $security;
  13.     }
  14.     protected function supports($attribute$subject): bool
  15.     {
  16.         return in_array($attribute, ['CAN_SWITCH_USER'])
  17.             && $subject instanceof UserInterface;
  18.     }
  19.     protected function voteOnAttribute($attribute$subjectTokenInterface $token): bool
  20.     {
  21.         $user $token->getUser();
  22.         // if the user is anonymous or if the subject is not a user, do not grant access
  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.             return true;
  29.         }
  30.         // check for any roles you want
  31.         if ($this->security->isGranted('ROLE_ADMIN')) {
  32.             if (!$subject->isAdmin()) {
  33.                 return true;
  34.             }
  35.         }
  36.         if ($this->security->isGranted('ROLE_SUPER_ADMIN')) {
  37.             return true;
  38.         }
  39.         /*
  40.          * or use some custom data from your User object
  41.         if ($user->isAllowedToSwitch()) {
  42.             return true;
  43.         }
  44.         */
  45.         return false;
  46.     }
  47. }