src/EventSubscriber/TokenSubscriber.php line 29

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Controller\API\TokenAuthenticatedController;
  4. use App\Services\UserService;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use Symfony\Component\Finder\Exception\AccessDeniedException;
  7. use Symfony\Component\HttpKernel\Event\ControllerEvent;
  8. use Symfony\Component\HttpKernel\KernelEvents;
  9. use Symfony\Contracts\Translation\TranslatorInterface;
  10. class TokenSubscriber implements EventSubscriberInterface
  11. {
  12.     private $userService;
  13.     private $translator;
  14.     /**
  15.      * @param UserService $userService
  16.      * @param TranslatorInterface $translator
  17.      */
  18.     public function __construct(UserService $userServiceTranslatorInterface $translator)
  19.     {
  20.         $this->userService $userService;
  21.         $this->translator $translator;
  22.     }
  23.     public function onKernelController(ControllerEvent $event)
  24.     {
  25.         $controller $event->getController();
  26.         if (is_array($controller)) {
  27.             $controller $controller[0];
  28.         }
  29.         if ($controller instanceof TokenAuthenticatedController) {
  30.             $token $event->getRequest()->headers->get('secret-token');
  31.             if (!$token) {
  32.                 throw new AccessDeniedException(
  33.                     $this->translator->trans('app.api.forbidden.text',
  34.                         [],
  35.                         null,
  36.                         $event->getRequest()->getLocale())
  37.                 );
  38.             }
  39.             $user $this->userService->findByToken($token);
  40.             if (!$user) {
  41.                 throw new AccessDeniedException(
  42.                     $this->translator->trans('app.api.forbidden.text',
  43.                         [],
  44.                         null,
  45.                         $event->getRequest()->getLocale())
  46.                 );
  47.             }
  48.         }
  49.     }
  50.     public static function getSubscribedEvents(): array
  51.     {
  52.         return [
  53.             KernelEvents::CONTROLLER => 'onKernelController'
  54.         ];
  55.     }
  56. }