src/Security/Voter/UserVoter.php line 17

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\Eg\Admin\Role;
  4. use App\Entity\Eg\Admin\User;
  5. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  6. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  7. use Symfony\Component\Security\Core\Security;
  8. /**
  9.  * Decyduje o dostępie do konta użytkownika. Dwie reguły:
  10.  *   VIEW            - rola okna "Użytkownicy" albo własne konto
  11.  *   CHANGE_PASSWORD - własne konto albo rola edycji użytkowników
  12.  * Wyjątek na własne konto jest konieczny przez "Zmień hasło" w menu użytkownika
  13.  */
  14. final class UserVoter extends Voter
  15. {
  16.     public const VIEW = 'EG_USER_VIEW';
  17.     public const CHANGE_PASSWORD = 'EG_USER_CHANGE_PASSWORD';
  18.     public const ATTRIBUTES = [self::VIEW, self::CHANGE_PASSWORD];
  19.     public function __construct(private readonly Security $security)
  20.     {
  21.     }
  22.     protected function supports(string $attribute, $subject): bool
  23.     {
  24.         return \in_array($attribute, self::ATTRIBUTES, true);
  25.     }
  26.     protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
  27.     {
  28.         if ($this->isOwnAccount($subject, $token)) {
  29.             return true;
  30.         }
  31.         if ($attribute === self::CHANGE_PASSWORD) {
  32.             // Cudze hasło może zmienić tylko ten, kto może edytować użytkowników.
  33.             return $this->security->isGranted(Role::ROLE_USERS_EDIT);
  34.         }
  35.         return $this->security->isGranted(Role::ROLE_USERS_VIEW);
  36.     }
  37.     private function isOwnAccount($subject, TokenInterface $token): bool
  38.     {
  39.         if (!$subject instanceof User) {
  40.             return false;
  41.         }
  42.         $current = $token->getUser();
  43.         return $current instanceof User
  44.             && $current->getId() !== null
  45.             && $current->getId() === $subject->getId();
  46.     }
  47. }