src/Security/Voter/UserVoter.php line 11

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  4. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  5. use Symfony\Component\Security\Core\User\UserInterface;
  6. use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface;
  7. use App\Entity\User as User;
  8. class UserVoter extends Voter
  9. {
  10.     const EDIT 'ROLE_USER_EDIT';
  11.     const DELETE 'ROLE_USER_DELETE';
  12.     private $decisionManager;
  13.     public function __construct(AccessDecisionManagerInterface $decisionManager)
  14.     {
  15.         $this->decisionManager $decisionManager;
  16.     }
  17.     protected function supports($attribute$subject)
  18.     {
  19.         // if the attribute isn't one we support, return false
  20.         if (!in_array($attribute, [self::EDITself::DELETE])) {
  21.             return false;
  22.         }
  23.         return true;
  24.     }
  25.     protected function voteOnAttribute($attribute$subjectTokenInterface $token)
  26.     {
  27.         $userLogged $token->getUser();
  28.         if (!$userLogged instanceof User) {
  29.             // the user must be logged in; if not, deny access
  30.             return false;
  31.         }
  32.         if ($this->decisionManager->decide($token, ['ROLE_SUPER_ADMIN'])) {
  33.             return true;
  34.         }
  35.         // you know $subject is a Post object, thanks to supports
  36.         $user $subject;
  37.         switch ($attribute) {
  38.             case self::EDIT:
  39.                 return $this->canEdit($user$userLogged);
  40.             case self::DELETE:
  41.                 return $this->canDelete($user$userLogged);
  42.         }
  43.         throw new \LogicException('This code should not be reached!');
  44.     }
  45.     private function canEdit($user$userLogged)
  46.     {
  47.         // if they can edit, they can view
  48.         if ($this->canDelete($user$userLogged)) {
  49.             return true;
  50.         }
  51.         return false;
  52.     }
  53.     private function canDelete($user$userLogged)
  54.     {
  55.         // this assumes that the data object has a getOwner() method
  56.         // to get the entity of the user who owns this data object
  57.         if ($user->getId() == $userLogged->getId()) {
  58.             return true;
  59.         }
  60.         if ($userLogged->hasRole('ROLE_ADMIN') && $user->hasRole('ROLE_USER')) {
  61.             return true;
  62.         }
  63.         return false;
  64.     }
  65. }