BankAccountVoter.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Security\Voter;
  4. use App\Entity\Access\Access;
  5. use App\Entity\Core\BankAccount;
  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. use Symfony\Component\Security\Core\User\UserInterface;
  10. class BankAccountVoter extends Voter
  11. {
  12. private Security $security;
  13. public function __construct(Security $security)
  14. {
  15. $this->security = $security;
  16. }
  17. protected function supports($attribute, $subject): bool
  18. {
  19. return in_array($attribute, ['BANK_ACCOUNT_READ', 'BANK_ACCOUNT_EDIT'])
  20. && $subject instanceof BankAccount;
  21. }
  22. /**
  23. * @param string $attribute
  24. * @param mixed $subject
  25. * @param TokenInterface $token
  26. * @return bool
  27. */
  28. protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool
  29. {
  30. /** @var Access $user */
  31. $user = $token->getUser();
  32. // if the user is anonymous, do not grant access
  33. if (!$user instanceof UserInterface) {
  34. return false;
  35. }
  36. switch ($attribute) {
  37. case 'BANK_ACCOUNT_READ':
  38. if($subject->getOrganization()->count() === 1){
  39. return $this->security->isGranted('ROLE_ORGANIZATION_VIEW')
  40. && $subject->getOrganization()->current()->getId() === $user->getOrganization()->getId();
  41. }
  42. break;
  43. case 'BANK_ACCOUNT_EDIT':
  44. if($subject->getOrganization()->count() === 1){
  45. return $this->security->isGranted('ROLE_ORGANIZATION')
  46. && $subject->getOrganization()->current()->getId() === $user->getOrganization()->getId();
  47. }
  48. break;
  49. }
  50. return false;
  51. }
  52. }