src/Security/Voter/FirmVoter.php line 13

Open in your IDE?
  1. <?php
  2. namespace MedBrief\MSR\Security\Voter;
  3. use MedBrief\MSR\Entity\Firm;
  4. use MedBrief\MSR\Entity\User;
  5. use Override;
  6. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  7. use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
  8. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  9. use Symfony\Component\Security\Core\User\UserInterface;
  10. class FirmVoter extends Voter
  11. {
  12. public const EDIT = 'EDIT';
  13. public const VIEW = 'VIEW';
  14. public const DELETE = 'DELETE';
  15. public function __construct(private readonly AuthorizationCheckerInterface $authorizationChecker)
  16. {
  17. }
  18. #[Override]
  19. protected function supports($attribute, $subject): bool
  20. {
  21. // replace with your own logic
  22. // https://symfony.com/doc/current/security/voters.html
  23. return in_array($attribute, [
  24. self::EDIT,
  25. self::VIEW,
  26. self::DELETE,
  27. ])
  28. && $subject instanceof Firm;
  29. }
  30. #[Override]
  31. protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool
  32. {
  33. $user = $token->getUser();
  34. // if the user is anonymous, do not grant access
  35. if (!$user instanceof UserInterface) {
  36. return false;
  37. }
  38. /** @var Firm $firm */
  39. $firm = $subject;
  40. if ($this->authorizationChecker->isGranted('ROLE_ADMIN', $user)) {
  41. return true;
  42. }
  43. if ($attribute === self::VIEW) {
  44. // A technical admin role on ONE clientArea is all that's required to view the firm.
  45. foreach ($firm->getClientAreas() as $clientArea) {
  46. if ($this->authorizationChecker->isGranted(sprintf('ROLE_ACCOUNT_%1$s_TECHNICAL_ADMIN', $clientArea->getId()), $clientArea) === true) {
  47. return true;
  48. }
  49. }
  50. }
  51. return false;
  52. }
  53. }