src/Authentication/EventSubscriber/GraphQlSubscriber.php line 48

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Authentication\EventSubscriber;
  4. use App\Base\Component\GraphQL\Parser;
  5. use App\Base\Model\GraphQLObject;
  6. use Pimcore\Bundle\DataHubBundle\Event\GraphQL\ExecutorEvents;
  7. use Pimcore\Bundle\DataHubBundle\Event\GraphQL\Model\ExecutorEvent;
  8. use Symfony\Component\DependencyInjection\ParameterBag\ContainerBagInterface;
  9. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  10. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  11. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  12. class GraphQlSubscriber implements EventSubscriberInterface
  13. {
  14.     /**
  15.      * @var TokenStorageInterface
  16.      */
  17.     private TokenStorageInterface $tokenStorage;
  18.     /** @var ContainerBagInterface  */
  19.     private ContainerBagInterface $params;
  20.     public function __construct(TokenStorageInterface $tokenStorageContainerBagInterface $params)
  21.     {
  22.         $this->tokenStorage $tokenStorage;
  23.         $this->params $params;
  24.     }
  25.     /**
  26.      * @inheritDoc
  27.      */
  28.     public static function getSubscribedEvents()
  29.     {
  30.         return [
  31.             ExecutorEvents::PRE_EXECUTE => 'onPreExecute',
  32.         ];
  33.     }
  34.     /**
  35.      * @param ExecutorEvent $event
  36.      * @return void
  37.      * @throws \Psr\Container\ContainerExceptionInterface
  38.      * @throws \Psr\Container\NotFoundExceptionInterface
  39.      */
  40.     public function onPreExecute(ExecutorEvent $event): void
  41.     {
  42.         if ($event->getQuery()) {
  43.             $token $this->tokenStorage->getToken();
  44.             if (!$token instanceof TokenInterface || $token->getUser() === 'anon.') {
  45.                 $graphQLObject Parser::createFromQuery($event->getQuery());
  46.                 $skipAuthCheck $graphQLObject->getOperationType() === GraphQLObject::OPERATION_TYPE_MUTATION
  47.                     && in_array($graphQLObject->getOperationName(), $this->params->get('app.pimcore.graphql.notAuthorizedMutationList'));
  48.                 if (!$skipAuthCheck) {
  49.                     $skipAuthCheck $graphQLObject->getOperationType() === GraphQLObject::OPERATION_TYPE_QUERY
  50.                         && in_array($graphQLObject->getOperationName(), $this->params->get('app.pimcore.graphql.notAuthorizedQueryList'));
  51.                 }
  52.                 if (!$skipAuthCheck) {
  53.                     throw new \Exception('User not authorized');
  54.                 }
  55.             }
  56.         }
  57.     }
  58. }