src/Security/Voter/SwitchToCustomerVoter.php line 31

Open in your IDE?
  1. <?php
  2. /*
  3. * Disclaimer: This source code is protected by copyright law and by
  4. * international conventions.
  5. *
  6. * Any reproduction or partial or total distribution of the source code, by any
  7. * means whatsoever, is strictly forbidden.
  8. *
  9. * Anyone not complies with these provisions will be guilty of the offense of
  10. * infringement and the penal sanctions provided for by law.
  11. *
  12. * © 2023 All rights reserved.
  13. */
  14. namespace App\Security\Voter;
  15. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  16. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  17. use Symfony\Component\Security\Core\User\UserInterface;
  18. use Symfony\Component\Security\Core\Security;
  19. /**
  20.  * Class SwitchToCustomerVoter
  21.  *
  22.  * @author Rémy P. <r.peyron@ingeno.eu>
  23.  * @package App\Security\Voter
  24.  */
  25. class SwitchToCustomerVoter extends Voter
  26. {
  27.     private $security;
  28.     public function __construct (Security $security)
  29.     {
  30.         $this->security $security;
  31.     }
  32.     protected function supports($attribute$subject): bool
  33.     {
  34.         return in_array($attribute, ['CAN_SWITCH_USER'])
  35.             && $subject instanceof UserInterface;
  36.     }
  37.     protected function voteOnAttribute($attribute$subjectTokenInterface $token): bool
  38.     {
  39.         $user $token->getUser();
  40.         // if the user is anonymous or if the subject is not a user, do not grant access
  41.         if (!$user instanceof UserInterface || !$subject instanceof UserInterface) {
  42.             return false;
  43.         }
  44.         // you can still check for ROLE_ALLOWED_TO_SWITCH
  45.         if ($this->security->isGranted('ROLE_ALLOWED_TO_SWITCH')) {
  46.             return true;
  47.         }
  48.         // check for any roles you want
  49.         if ($this->security->isGranted('ROLE_TECH_SUPPORT')) {
  50.             return true;
  51.         }
  52.         /*
  53.          * or use some custom data from your User object
  54.         if ($user->isAllowedToSwitch()) {
  55.             return true;
  56.         }
  57.         */
  58.         return false;
  59.     }
  60. }