src/Security/Core/UserVoter.php line 12

Open in your IDE?
  1. <?php
  2. namespace App\Security\Core;
  3. use App\Entity\Core\PublisherPermission;
  4. use Doctrine\ORM\EntityManagerInterface;
  5. use App\Entity\User\User;
  6. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  7. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  8. use Symfony\Component\Security\Core\Security;
  9. class UserVoter extends Voter
  10. {
  11. const PERMISSION = 'userEntityPermission';
  12. const INDEX_ACTION = 'userIndexAction';
  13. const NEW_ACTION = 'userNewAction';
  14. const EDIT_ACTION = 'userEditAction';
  15. private EntityManagerInterface $em;
  16. private Security $security;
  17. public function __construct(EntityManagerInterface $em, Security $security)
  18. {
  19. $this->em = $em;
  20. $this->security = $security;
  21. }
  22. /**
  23. * @inheritDoc
  24. */
  25. protected function supports(string $attribute, $subject): bool
  26. {
  27. // For index and new, $subject will always be null. For permission, it will be null when trying to create a new entity.
  28. if (in_array($attribute, [self::INDEX_ACTION, self::NEW_ACTION, self::PERMISSION])) {
  29. return true;
  30. }
  31. if ($attribute == self::EDIT_ACTION) {
  32. return $subject instanceof User;
  33. }
  34. return false;
  35. }
  36. /**
  37. * @inheritDoc
  38. */
  39. protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
  40. {
  41. if ($attribute === self::INDEX_ACTION) {
  42. // Allow everyone to list - the entity permissions will still apply and hide entities you are not allowed
  43. // to access.
  44. return true;
  45. }
  46. if ($attribute === self::NEW_ACTION || $attribute === self::PERMISSION && $subject === null) {
  47. // Only super admins should be allowed to create new users.
  48. return $this->security->isGranted('ROLE_SUPER_ADMIN');
  49. }
  50. if (!$subject instanceof User) {
  51. throw new \LogicException("Invalid type for voter and attribute.");
  52. }
  53. return $this->checkEntityPermissions($attribute, $subject, $token);
  54. }
  55. public function checkEntityPermissions(string $attribute, User $subject, TokenInterface $token): bool
  56. {
  57. if ($this->security->isGranted('ROLE_ADMIN')) {
  58. return true;
  59. }
  60. if ($this->security->isGranted('ROLE_EDITOR')) {
  61. $sharedPermissions = $this->em->getRepository(PublisherPermission::class)
  62. ->findAllSharedActiveForUsers($token->getUser(), $subject);
  63. return !empty($sharedPermissions);
  64. }
  65. // Authors
  66. return false;
  67. }
  68. }