src/Listener/ApiAccessSubscriber.php line 27

Open in your IDE?
  1. <?php
  2. namespace App\Listener;
  3. use App\Controller\ApiAccessController;
  4. use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
  5. use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
  6. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  7. use Symfony\Component\HttpKernel\KernelEvents;
  8. use Symfony\Component\Security\Core\Exception\AccessDeniedException;
  9. /**
  10.  * Verifie l'origine de la requete
  11.  */
  12. class ApiAccessSubscriber implements EventSubscriberInterface
  13. {
  14.     private $authorizationChecker;
  15.     private $env;
  16.     public function __construct($authorizationChecker$env)
  17.     {
  18.         $this->authorizationChecker $authorizationChecker;
  19.         $this->env                  $env;
  20.     }
  21.     public function onKernelController(FilterControllerEvent $event)
  22.     {
  23.         $controller $event->getController();
  24.         if (!is_array($controller)) {
  25.             return;
  26.         }
  27.         if ($controller[0] instanceof ApiAccessController) {
  28.             if (false == $this->authorizationChecker->isGranted('IS_AUTHENTICATED_FULLY')) {
  29.                 $headers $event->getRequest()->headers;
  30.                 $hosts   'localhost:8000 apitest.pretemoitonchat.com apistaging.pretemoitonchat.com staging.pretemoitonchat.com pmtc.pretemoitonchat.com pretemoitonchat.com apipmtc.pretemoitonchat.com api.pretemoitonchat.com';
  31.                 $origins 'http://localhost:8000 http://localhost:8080 https://pmtc.pretemoitonchat.com https://staging.pretemoitonchat.com https://pretemoitonchat.com';
  32.                 if ($host $headers->get('host')) {
  33.                     if (!strstr($hosts$host)) {
  34.                         throw new AccessDeniedException();
  35.                     } else {
  36.                         if ($origin $headers->get('origin')) {
  37.                             if (!strstr($origins$origin)) {
  38.                                 throw new AccessDeniedException();
  39.                             }
  40.                             else {
  41.                               return;
  42.                             }
  43.                         } else {
  44.                             if ($this->env == 'dev') {
  45.                               return;
  46.                             }
  47.                             throw new AccessDeniedException();
  48.                         }
  49.                     }
  50.                 }
  51.             }
  52.         }
  53.     }
  54.     public static function getSubscribedEvents()
  55.     {
  56.         return array(
  57.             KernelEvents::CONTROLLER => 'onKernelController',
  58.         );
  59.     }
  60. }