src/Security/SwitchToUserVoter.php line 10

Open in your IDE?
  1. <?php
  2. namespace App\Security;
  3. use App\Entity\User;
  4. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  5. use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface;
  6. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  7. class SwitchToUserVoter extends Voter
  8. {
  9.     /** @var AccessDecisionManagerInterface */
  10.     private $decisionManager;
  11.     /**
  12.      * @param AccessDecisionManagerInterface $decisionManager
  13.      */
  14.     public function __construct(AccessDecisionManagerInterface $decisionManager)
  15.     {
  16.         $this->decisionManager $decisionManager;
  17.     }
  18.     /**
  19.      * {@inheritdoc}
  20.      */
  21.     protected function supports($attribute$subject)
  22.     {
  23.         return 'ROLE_ALLOWED_TO_SWITCH' === $attribute
  24.             && $subject instanceof User;
  25.     }
  26.     /**
  27.      * {@inheritdoc}
  28.      */
  29.     protected function voteOnAttribute($attribute$subjectTokenInterface $token)
  30.     {
  31.         $user $token->getUser();
  32.         // reject when unauthenticated or subject is not a User
  33.         if (!$user instanceof User || !$subject instanceof User) {
  34.             return false;
  35.         }
  36.         // allow when ROLE_ALLOWED_TO_SWITCH already granted by other voters
  37.         if ($this->decisionManager->decide($token, ['ROLE_ALLOWED_TO_SWITCH'])) {
  38.             return true;
  39.         }
  40.         // allow when user has ROLE_ADMIN
  41.         if ($this->decisionManager->decide($token, ['ROLE_ADMIN'])) {
  42.             return true;
  43.         }
  44.         // allow when user has custom system-admin permission
  45.         if ($user->isAllowSystemAdmin()) {
  46.             return true;
  47.         }
  48.         return false;
  49.     }
  50. }