src/Magazzino/Security/MagazzinoVoter.php line 23

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Magazzino\Security;
  4. use App\Magazzino\Service\ModuloConfigService;
  5. use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
  6. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  7. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  8. /**
  9. * Voter granulare per il modulo magazzino.
  10. *
  11. * Attributi supportati:
  12. * - magazzino.section.<key> es. magazzino.section.articoli
  13. * - magazzino.entity.<name>.view|edit|delete|create
  14. *
  15. * Combina due controlli:
  16. * 1) ModuloConfigService dice se la sezione รจ abilitata in config
  17. * 2) Symfony role hierarchy controlla che l'utente abbia il ruolo richiesto
  18. */
  19. class MagazzinoVoter extends Voter
  20. {
  21. public const SECTION_PREFIX = 'magazzino.section.';
  22. public const ENTITY_PREFIX = 'magazzino.entity.';
  23. public function __construct(
  24. private readonly ModuloConfigService $config,
  25. private readonly AuthorizationCheckerInterface $authChecker,
  26. ) {
  27. }
  28. protected function supports($attribute, $subject)
  29. {
  30. return is_string($attribute) && (
  31. str_starts_with($attribute, self::SECTION_PREFIX)
  32. || str_starts_with($attribute, self::ENTITY_PREFIX)
  33. );
  34. }
  35. protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
  36. {
  37. if (!$token->getUser()) {
  38. return false;
  39. }
  40. if (str_starts_with($attribute, self::SECTION_PREFIX)) {
  41. $key = substr($attribute, strlen(self::SECTION_PREFIX));
  42. $section = $this->config->getSection($key);
  43. if ($section === null || empty($section['enabled'])) {
  44. return false;
  45. }
  46. $role = $section['role'] ?? 'ROLE_MAGAZZINO_OPERATOR';
  47. return $this->authChecker->isGranted($role);
  48. }
  49. if (str_starts_with($attribute, self::ENTITY_PREFIX)) {
  50. $tail = substr($attribute, strlen(self::ENTITY_PREFIX));
  51. [$entity, $op] = array_pad(explode('.', $tail, 2), 2, 'view');
  52. $needed = match ($op) {
  53. 'view' => 'ROLE_MAGAZZINO_OPERATOR',
  54. 'create' => 'ROLE_MAGAZZINO_OPERATOR',
  55. 'edit' => 'ROLE_MAGAZZINO_OPERATOR',
  56. 'delete' => 'ROLE_MAGAZZINO_MANAGER',
  57. default => 'ROLE_MAGAZZINO_MANAGER',
  58. };
  59. return $this->authChecker->isGranted($needed);
  60. }
  61. return false;
  62. }
  63. }