<?php
namespace App\Listener;
use App\Controller\ApiAccessController;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
/**
* Verifie l'origine de la requete
*/
class ApiAccessSubscriber implements EventSubscriberInterface
{
private $authorizationChecker;
private $env;
public function __construct($authorizationChecker, $env)
{
$this->authorizationChecker = $authorizationChecker;
$this->env = $env;
}
public function onKernelController(FilterControllerEvent $event)
{
$controller = $event->getController();
if (!is_array($controller)) {
return;
}
if ($controller[0] instanceof ApiAccessController) {
if (false == $this->authorizationChecker->isGranted('IS_AUTHENTICATED_FULLY')) {
$headers = $event->getRequest()->headers;
$hosts = 'localhost:8000 apitest.pretemoitonchat.com apistaging.pretemoitonchat.com staging.pretemoitonchat.com pmtc.pretemoitonchat.com pretemoitonchat.com apipmtc.pretemoitonchat.com api.pretemoitonchat.com';
$origins = 'http://localhost:8000 http://localhost:8080 https://pmtc.pretemoitonchat.com https://staging.pretemoitonchat.com https://pretemoitonchat.com';
if ($host = $headers->get('host')) {
if (!strstr($hosts, $host)) {
throw new AccessDeniedException();
} else {
if ($origin = $headers->get('origin')) {
if (!strstr($origins, $origin)) {
throw new AccessDeniedException();
}
else {
return;
}
} else {
if ($this->env == 'dev') {
return;
}
throw new AccessDeniedException();
}
}
}
}
}
}
public static function getSubscribedEvents()
{
return array(
KernelEvents::CONTROLLER => 'onKernelController',
);
}
}