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 EasyCorp\Bundle\EasyAdminBundle\Security\Permission;
  5. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  6. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  7. use Symfony\Component\Security\Core\User\UserInterface;
  8. class UserVoter extends Voter
  9. {
  10.     protected function supports($attribute$subject)
  11.     {
  12.         // dump([
  13.         //     "supports" => $attribute,
  14.         //     'subject' => $subject,
  15.         // ]);
  16.         // replace with your own logic
  17.         // https://symfony.com/doc/current/security/voters.html
  18.         return in_array($attribute, [Permission::EA_ACCESS_ENTITY])
  19.             && $subject->getInstance() instanceof User;
  20.     }
  21.     protected function voteOnAttribute($attribute$subjectTokenInterface $token)
  22.     {
  23.         $user $token->getUser();
  24.         // if the user is anonymous, do not grant access
  25.         if (!$user instanceof UserInterface) {
  26.             return false;
  27.         }
  28.         // ... (check conditions and return true to grant permission) ...
  29.         switch ($attribute) {
  30.             case Permission::EA_ACCESS_ENTITY:
  31.                 // dump([
  32.                 //     "voteOnAttribute" => $attribute,
  33.                 //     'subject' => $subject,
  34.                 //     'token' => $token,
  35.                 // ]);
  36.                 switch ($subject->getFqcn()) {
  37.                     case User::class:
  38.                         // User can access his own record
  39.                         return $subject->getInstance() == $user;
  40.                 }
  41.                 break;
  42.         }
  43.         throw new \LogicException('This code should not be reached!');
  44.     }
  45. }