src/Security/Voter/BackendSuperUserVoter.php line 13

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\User;
  4. use App\Utils\Commons;
  5. use LogicException;
  6. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  7. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  8. use Symfony\Component\Security\Core\Security;
  9. use Symfony\Component\Security\Core\User\UserInterface;
  10. class BackendSuperUserVoter extends Voter
  11. {
  12.     /**
  13.      * @var Security
  14.      */
  15.     private $security;
  16.     /**
  17.      * @var Commons
  18.      */
  19.     private $commons;
  20.     /**
  21.      * @var array
  22.      */
  23.     private $permissions;
  24.     /**
  25.      * BackendSuperUserVoter constructor.
  26.      * @param Security $security
  27.      * @param Commons $commons
  28.      */
  29.     public function __construct(Security $securityCommons $commons)
  30.     {
  31.         $this->security $security;
  32.         $this->commons $commons;
  33.         $this->permissions = [];
  34.     }
  35.     /**
  36.      * @param string $attribute
  37.      * @param mixed $subject
  38.      * @return bool
  39.      */
  40.     protected function supports($attribute$subject): bool
  41.     {
  42.         if (!in_array($attribute,
  43.             ['SUPER_USER_RIGHTS']
  44.         )) {
  45.             return false;
  46.         }
  47.         return true;
  48.     }
  49.     /**
  50.      * @param string $attribute
  51.      * @param mixed $subject
  52.      * @param TokenInterface $token
  53.      * @return bool
  54.      */
  55.     protected function voteOnAttribute($attribute$subjectTokenInterface $token): bool
  56.     {
  57.         /** @var User $user */
  58.         $user $token->getUser();
  59.         // if the user is anonymous, do not grant access
  60.         if (!$user instanceof UserInterface) {
  61.             return false;
  62.         }
  63.         $this->permissions $this->commons->getBackendPermissions($user);
  64.         switch ($attribute) {
  65.             case 'SUPER_USER_RIGHTS':
  66.                 return $this->canHave();
  67.         }
  68.         throw new  LogicException('Invalid attribute: ' $attribute);
  69.     }
  70.     /**
  71.      * Return True if have Super View Permission else return false
  72.      * @return bool
  73.      */
  74.     private function canHave(): bool
  75.     {
  76.         if (array_key_exists('superUser'$this->permissions)) {
  77.             if (in_array('Yes'$this->permissions['superUser'])) {
  78.                 return true;
  79.             }
  80.         }
  81.         return false;
  82.     }
  83. }