src/EventSubscriber/ProjectKeySubscriber.php line 26

Open in your IDE?
  1. <?php
  2.     namespace App\EventSubscriber;
  3.     use App\Controller\API\WhiteMark\ProjectKeyAuthenticatedController;
  4.     use App\Services\DTV\YamlConfig\YamlReader;
  5.     use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6.     use Symfony\Component\HttpKernel\Event\ControllerEvent;
  7.     use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
  8.     use Symfony\Component\HttpKernel\KernelEvents;
  9.     /**
  10.      * Permet de vérifier quand un controller API est appelé que la valeur Platform-Key est valide dans le HEADER
  11.      */
  12.     class ProjectKeySubscriber implements EventSubscriberInterface
  13.     {
  14.         private YamlReader $yamlReader;
  15.         /**
  16.          * @param   YamlReader  $yamlReader
  17.          */
  18.         public function __construct(YamlReader $yamlReader) { $this->yamlReader $yamlReader; }
  19.         public function onKernelController(ControllerEvent $event)
  20.         {
  21.             $controller $event->getController();
  22.             // when a controller class defines multiple action methods, the controller
  23.             // is returned as [$controllerInstance, 'methodName']
  24.             if (is_array($controller)) {
  25.                 $controller $controller];
  26.             }
  27.             if ($controller instanceof ProjectKeyAuthenticatedController) {
  28.                 $host    $this->remove_http($event->getRequest()->getHost());
  29.                 $referer $this->remove_http($event->getRequest()->headers->get('referer'));
  30.                 // ON check pas la clé du projet quand on est sur le swagger
  31.                 if ($host.'/wm-api/doc' === $referer || $host.'/wm-api/doc/' === $referer) {
  32.                     return;
  33.                 }
  34.                 $projectKey $event->getRequest()->headers->get('Project-Key');
  35.                 if ($projectKey !== $this->yamlReader->getProjectKey()) {
  36.                     throw new AccessDeniedHttpException('This action needs a valid project key!');
  37.                 }
  38.             }
  39.         }
  40.         public static function getSubscribedEvents()
  41.         {
  42.             return [
  43.                 KernelEvents::CONTROLLER => 'onKernelController',
  44.             ];
  45.         }
  46.         private function remove_http($url)
  47.         {
  48.             $disallowed = ['http://''https://'];
  49.             foreach ($disallowed as $d) {
  50.                 if (strpos($url$d) === 0) {
  51.                     return str_replace($d''$url);
  52.                 }
  53.             }
  54.             return $url;
  55.         }
  56.     }