src/Security/Voter/UserVoter.php line 9

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. class UserVoter extends Voter
  7. {
  8.     public const VIEW_EDIT 'VIEW_EDIT';
  9.     protected function supports(string $attribute$subject): bool
  10.     {
  11.         // replace with your own logic
  12.         // https://symfony.com/doc/current/security/voters.html
  13.         return in_array($attribute, [self::VIEW_EDIT])
  14.             && $subject instanceof \App\Entity\User;
  15.     }
  16.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token): bool
  17.     {
  18.         $user $token->getUser();
  19.         // if the user is anonymous, do not grant access
  20.         if (!$user instanceof UserInterface) {
  21.             return false;
  22.         }
  23.         // ... (check conditions and return true to grant permission) ...
  24.         switch ($attribute) {
  25.             case self::VIEW_EDIT:
  26.                 // logic to determine if the user can EDIT
  27.                 // if the logged in user is the same as the editing user -> allow editing
  28.                 return $subject->getId() === $user->getId();
  29.                 break;
  30.         }
  31.         return false;
  32.     }
  33. }