src/ApiPlatform/Voter/UserVoter.php line 10

Open in your IDE?
  1. <?php
  2. namespace App\ApiPlatform\Voter;
  3. use App\Entity\User;
  4. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  5. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  6. use Symfony\Component\Security\Core\Security;
  7. class UserVoter extends Voter
  8. {
  9.     public const EDIT 'EDIT';
  10.     public const VIEW 'VIEW';
  11.     public const DELETE 'DELETE';
  12.     public function __construct(private readonly Security $security)
  13.     {
  14.     }
  15.     protected function supports(string $attribute$subject): bool
  16.     {
  17.         if (!$subject instanceof User) {
  18.             return false;
  19.         }
  20.         
  21.         return in_array($attribute, [self::EDITself::VIEWself::DELETE]);
  22.     }
  23.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token): bool
  24.     {
  25.         $currentUser $token->getUser();
  26.         if (!$currentUser instanceof User) {
  27.             return false;
  28.         }
  29.         
  30.         // If user is a master admin, allow all operations
  31.         if ($currentUser->isMasterAdmin()) {
  32.             return true;
  33.         }
  34.         
  35.         // Users can only edit/view their own data
  36.         $user $subject;
  37.         
  38.         switch ($attribute) {
  39.             case self::EDIT:
  40.                 return $currentUser->getId() === $user->getId();
  41.             case self::VIEW:
  42.                 return $currentUser->getId() === $user->getId();
  43.             case self::DELETE:
  44.                 return false// Regular users can't delete accounts
  45.         }
  46.         return false;
  47.     }
  48. }