src/Security/Voter/UserVoter.php line 11

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\User;
  4. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  5. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  6. use Symfony\Component\Security\Core\Security;
  7. use Symfony\Component\Security\Core\User\UserInterface;
  8. class UserVoter extends Voter
  9. {
  10.     public const USER_VIEW 'user_view';
  11.     public const USER_CREATE 'user_create';
  12.     public const USER_EDIT 'user_edit';
  13.     public const USER_DELETE 'user_delete';
  14.     public const USER_RECOVERY 'user_recovery';
  15.     public const USER_CHANGE_PASSWORD 'user_change_password';
  16.     public const USERS_MANAGE 'users_manage';
  17.     private Security $security;
  18.     public function __construct(Security $security)
  19.     {
  20.         $this->security $security;
  21.     }
  22.     /**
  23.      * @param string $attribute
  24.      * @param mixed $subject
  25.      * @return bool
  26.      */
  27.     protected function supports(string $attribute$subject): bool
  28.     {
  29.         return in_array($attribute, [
  30.             self::USER_VIEW,
  31.             self::USER_CREATE,
  32.             self::USER_EDIT,
  33.             self::USER_DELETE,
  34.             self::USER_RECOVERY,
  35.             self::USER_CHANGE_PASSWORD,
  36.             self::USERS_MANAGE,
  37.         ]);
  38.     }
  39.     /**
  40.      * @param string $attribute
  41.      * @param mixed $subject
  42.      * @param TokenInterface $token
  43.      * @return bool
  44.      */
  45.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token): bool
  46.     {
  47.         $user $token->getUser();
  48.         // if the user is anonymous, do not grant access
  49.         if (!$user instanceof UserInterface) {
  50.             return false;
  51.         }
  52.         /** @var User $userSubject*/
  53.         $userSubject $subject;
  54.         // ROLE_SUPER_ADMIN can do anything!
  55.         if ($this->security->isGranted('ROLE_SUPER_ADMIN')) {
  56.             return true;
  57.         }
  58.         switch ($attribute) {
  59.             case self::USER_VIEW:
  60.             case self::USER_DELETE:
  61.             case self::USER_RECOVERY:
  62.             case self::USER_CREATE:
  63.             case self::USERS_MANAGE:
  64.                 return false;
  65.             case self::USER_EDIT:
  66.             case self::USER_CHANGE_PASSWORD:
  67.                 return $user->getUsername() === $userSubject->getEmail();
  68.         }
  69.         throw new \LogicException('This code should not be reached!');
  70.     }
  71. }