src/Security/Voter/UserVoter.php line 12

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Security\Voter;
  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. use Symfony\Component\Security\Core\User\UserInterface;
  8. class UserVoter extends Voter
  9. {
  10. public function __construct(private readonly Security $security)
  11. {
  12. }
  13. protected function supports($attribute, $subject): bool
  14. {
  15. // only vote on `User` objects
  16. if (!$subject instanceof UserInterface) {
  17. return false;
  18. }
  19. // if the attribute isn't one we support, return false
  20. return $attribute == 'edit';
  21. }
  22. protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool
  23. {
  24. $user = $token->getUser();
  25. // if the user is anonymous, do not grant access
  26. if (!$user instanceof UserInterface) {
  27. return false;
  28. }
  29. // ROLE_CHIEF can do anything! The power!
  30. if ($this->security->isGranted('ROLE_CHIEF')) {
  31. return true;
  32. }
  33. return match ($attribute) {
  34. // Users may edit themself
  35. 'edit' => $user === $subject,
  36. default => false,
  37. };
  38. }
  39. }