src/Security/Core/UserVoter.php line 13

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