src/EventSubscriber/TokenSubscriber.php line 20

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Controller\TokenAuthenticatedController;
  4. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  5. use Symfony\Component\HttpKernel\Event\ControllerEvent;
  6. use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
  7. use Symfony\Component\HttpKernel\KernelEvents;
  8. class TokenSubscriber implements EventSubscriberInterface
  9. {
  10.     private $tokens;
  11.     public function __construct($tokens)
  12.     {
  13.         $this->tokens $tokens;
  14.     }
  15.     public function onKernelController(ControllerEvent $event)
  16.     {
  17.         $controller $event->getController();
  18.         if (!is_array($controller)) {
  19.             return;
  20.         }
  21.         if ($controller[0] instanceof TokenAuthenticatedController) {
  22.             $token $event->getRequest()->headers->get('x-api-key');
  23.             if (!in_array($token$this->tokens)) {
  24.                 throw new AccessDeniedHttpException('This action needs a valid token!');
  25.             }
  26.         }
  27.     }
  28.     public static function getSubscribedEvents()
  29.     {
  30.         return [
  31.             KernelEvents::CONTROLLER => 'onKernelController',
  32.         ];
  33.     }
  34. }