src/Security/Voter/UserVoter.php line 14

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\Course;
  4. use App\Entity\Job\Lecturer;
  5. use App\Entity\User;
  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. class UserVoter extends Voter
  10. {
  11.     const READ 'USER_READ';
  12.     const UPDATE 'USER_UPDATE';
  13.     const DELETE 'USER_DELETE';
  14.     private $security;
  15.     /**
  16.      * @param Security $security
  17.      */
  18.     public function __construct(Security $security)
  19.     {
  20.         $this->security $security;
  21.     }
  22.     protected function supports($attribute$subject)
  23.     {
  24.         // if the attribute isn't one we support, return false
  25.         if (!in_array($attribute, [self::READself::UPDATEself::DELETE])) {
  26.             return false;
  27.         }
  28.         // only vote on User objects inside this voter
  29.         if (!$subject instanceof User) {
  30.             return false;
  31.         }
  32.         return true;
  33.     }
  34.     protected function voteOnAttribute($attribute$subjectTokenInterface $token)
  35.     {
  36.         $currentUser $token->getUser();
  37.         if (!$currentUser instanceof User) {
  38.             // the user must be logged in; if not, deny access
  39.             return false;
  40.         }
  41.         if ($this->security->isGranted(User::ROLE_ADMIN)) {
  42.             return true;
  43.         }
  44.         switch ($attribute) {
  45.             case self::READ:
  46.                 return $this->canRead($currentUser);
  47.             case self::UPDATE:
  48.                 return $this->canUpdate($currentUser);
  49.             case self::DELETE:
  50.                 return $this->canDelete($currentUser);
  51.         }
  52.         throw new \LogicException('This code should not be reached!');
  53.     }
  54.     private function canRead(User $currentUser)
  55.     {
  56.         if ($this->security->isGranted(User::ROLE_LECTURER)) {
  57.             return true;
  58.         }
  59.         return false;
  60.     }
  61.     private function canUpdate(User $currentUser)
  62.     {
  63.         if ($this->security->isGranted(User::ROLE_LECTURER)) {
  64.             return true;
  65.         }
  66.         return false;
  67.     }
  68.     private function canDelete(User $currentUser)
  69.     {
  70.         return false;
  71.     }
  72. }