src/Security/Voter/ApiRoleVoter.php line 12

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use Oz\ApiNvl\Model\User;
  4. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  5. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  6. /**
  7.  *
  8.  */
  9. class ApiRoleVoter extends Voter
  10. {
  11.     public const ADD_USER 'ADD_USER';
  12.     /**
  13.      * Determines if the attribute and subject are supported by this voter.
  14.      *
  15.      * @param string $attribute An attribute
  16.      * @param mixed  $subject   The subject to secure, e.g. an object the user wants to access or any other PHP type
  17.      *
  18.      * @return bool
  19.      */
  20.     protected function supports(string $attribute$subject): bool
  21.     {
  22.         return $attribute == self::ADD_USER;
  23.     }
  24.     /**
  25.      * Perform a single access check operation on a given attribute, subject and token.
  26.      * It is safe to assume that $attribute and $subject already passed the "supports()" method check.
  27.      *
  28.      * @param string         $attribute
  29.      * @param mixed          $subject
  30.      * @param TokenInterface $token
  31.      *
  32.      * @return bool
  33.      */
  34.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token): bool
  35.     {
  36.         $user $token->getUser();
  37.         if (!$user instanceof User) {
  38.             return false;
  39.         }
  40.         if ($attribute == self::ADD_USER) {
  41.             return $this->thisUserCanAddOtherUsers($user);
  42.         }
  43.         return false;
  44.     }
  45.     /**
  46.      *
  47.      * @param User $user
  48.      *
  49.      * @return bool
  50.      */
  51.     private function thisUserCanAddOtherUsers(User $user): bool
  52.     {
  53.         return in_array($user->getApiRole(), ['admin']);
  54.     }
  55. }