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\Security;
  6. class UserVoter extends Voter
  7. {
  8.     public const EDIT 'POST_EDIT';
  9.     public const VIEW 'POST_VIEW';
  10.     public const ADD 'POST_ADD';
  11.     public const DELETE 'POST_DELETE';
  12.     public function __construct( private readonly Security $security ) {}
  13.     protected function supports(string $attribute$subject): bool
  14.     {
  15.         // replace with your own logic
  16.         // https://symfony.com/doc/current/security/voters.html
  17.         return in_array($attribute, [self::EDITself::VIEWself::ADDself::DELETE])
  18.             && $subject instanceof \App\Entity\User;
  19.     }
  20.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token): bool
  21.     {
  22.         $user $this->security->getUser();
  23.         $itsMe = ( $user == $subject ); 
  24.         $isMyOrganization = ( $user->getOrganization() == $subject->getOrganization() );
  25.         if ($this->security->isGranted('ROLE_ADMIN')) {
  26.             return true;
  27.         
  28.         } else if ($this->security->isGranted('ROLE_MANAGER')) {
  29.             switch ( $attribute ) {
  30.                 case self::ADD:
  31.                     return true;
  32.                 case self::VIEW:
  33.                 case self::EDIT:
  34.                     return $isMyOrganization;
  35.                 default:
  36.                     return false;
  37.             }
  38.         } else if ($this->security->isGranted('ROLE_USER')) {
  39.             switch ( $attribute ) {
  40.                 case self::VIEW:
  41.                 case self::EDIT:
  42.                     return $itsMe;
  43.                 default:
  44.                     return false;
  45.             }
  46.         }
  47.         return false;
  48.     }
  49. }