BankAccountVoter.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. public function __construct(private Security $security)
  13. { }
  14. protected function supports($attribute, $subject): bool
  15. {
  16. return in_array($attribute, ['BANK_ACCOUNT_READ', 'BANK_ACCOUNT_EDIT', 'BANK_ACCOUNT_DELETE'])
  17. && $subject instanceof BankAccount;
  18. }
  19. /**
  20. * @param string $attribute
  21. * @param mixed $subject
  22. * @param TokenInterface $token
  23. * @return bool
  24. */
  25. protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
  26. {
  27. /** @var Access $user */
  28. $user = $token->getUser();
  29. // if the user is anonymous, do not grant access
  30. if (!$user instanceof UserInterface) {
  31. return false;
  32. }
  33. switch ($attribute) {
  34. case 'BANK_ACCOUNT_READ':
  35. if($subject->getOrganization()->count() === 1){
  36. return $this->security->isGranted('ROLE_ORGANIZATION_VIEW')
  37. && $subject->getOrganization()->current()->getId() === $user->getOrganization()->getId();
  38. }
  39. break;
  40. case 'BANK_ACCOUNT_EDIT':
  41. case 'BANK_ACCOUNT_DELETE':
  42. if($subject->getOrganization()->count() === 1){
  43. return $this->security->isGranted('ROLE_ORGANIZATION')
  44. && $subject->getOrganization()->current()->getId() === $user->getOrganization()->getId();
  45. }
  46. break;
  47. }
  48. return false;
  49. }
  50. }