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, $subject, TokenInterface $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_ADMIN')) {
  28.             return true;
  29.         }
  30.         // check for any roles you want
  31.         if ($this->security->isGranted('ROLE_CLOUD_TRAINER')) {
  32.             if ($this->security->getUser()->getGroup()->getSite()->getCustomer()->getAllowTrainerSigninAdmin()) {
  33.                 if (in_array('ROLE_CUSTOMER', $subject->getRoles()) && $subject->getVerified() && $subject->getActive() && $subject->getCustomerId() == $this->security->getUser()->getGroup()->getSite()->getCustomerId()) {
  34.                     return true;
  35.                 }
  36.             }
  37.         }
  38.         if ($this->security->isGranted('ROLE_MASTER_TRAINER')) {
  39.             if ($this->security->getUser()->getCustomer()->getAllowMastertrainerSigninAdmin()) {
  40.                 if (in_array('ROLE_CUSTOMER', $subject->getRoles()) && $subject->getVerified() && $subject->getActive() && $subject->getCustomerId() == $this->security->getUser()->getCustomerId()) {
  41.                     return true;
  42.                 }
  43.             }
  44.         }
  45.         return false;
  46.     }
  47. }