src/Security/Voter/UserVoter.php line 11

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use ApiPlatform\Core\Bridge\Doctrine\Orm\Paginator;
  4. use App\Entity\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\User\UserInterface;
  8. class UserVoter extends Voter
  9. {
  10.     public const VIEW_NOTIFICATIONS 'VIEW_NOTIFICATIONS';
  11.     protected function supports(string $attributemixed $subject): bool
  12.     {
  13.         return in_array($attribute, [
  14.                 self::VIEW_NOTIFICATIONS,
  15.             ])
  16.             && ($subject instanceof Paginator
  17.             || $subject instanceof User)
  18.         ;
  19.     }
  20.     protected function voteOnAttribute(string $attributemixed $subjectTokenInterface $token): bool
  21.     {
  22.         /**
  23.          * @var User $user
  24.          */
  25.         $user $token->getUser();
  26.         // if the user is anonymous, do not grant access
  27.         if (!$user instanceof UserInterface) {
  28.             return false;
  29.         }
  30.         if (self::VIEW_NOTIFICATIONS === $attribute) {
  31.             // TODO this should just be temporary until Api Platform allows security check on the owning side
  32.             if ($subject instanceof Paginator) {
  33.                 $query $subject
  34.                     ->getQuery()
  35.                 ;
  36.                 $queryParameters $query->getParameters();
  37.                 $email $queryParameters[0]
  38.                     ->getValue()
  39.                 ;
  40.             } else {
  41.                 $email $subject->getEmail();
  42.             }
  43.             return $user->getEmail() === $email;
  44.         }
  45.         return false;
  46.     }
  47. }