<?php
namespace App\EventSubscriber;
use App\Controller\API\WhiteMark\ProjectKeyAuthenticatedController;
use App\Services\DTV\YamlConfig\YamlReader;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\KernelEvents;
/**
* Permet de vérifier quand un controller API est appelé que la valeur Platform-Key est valide dans le HEADER
*/
class ProjectKeySubscriber implements EventSubscriberInterface
{
private YamlReader $yamlReader;
/**
* @param YamlReader $yamlReader
*/
public function __construct(YamlReader $yamlReader) { $this->yamlReader = $yamlReader; }
public function onKernelController(ControllerEvent $event)
{
$controller = $event->getController();
// when a controller class defines multiple action methods, the controller
// is returned as [$controllerInstance, 'methodName']
if (is_array($controller)) {
$controller = $controller[ 0 ];
}
if ($controller instanceof ProjectKeyAuthenticatedController) {
$host = $this->remove_http($event->getRequest()->getHost());
$referer = $this->remove_http($event->getRequest()->headers->get('referer'));
// ON check pas la clé du projet quand on est sur le swagger
if ($host.'/wm-api/doc' === $referer || $host.'/wm-api/doc/' === $referer) {
return;
}
$projectKey = $event->getRequest()->headers->get('Project-Key');
if ($projectKey !== $this->yamlReader->getProjectKey()) {
throw new AccessDeniedHttpException('This action needs a valid project key!');
}
}
}
public static function getSubscribedEvents()
{
return [
KernelEvents::CONTROLLER => 'onKernelController',
];
}
private function remove_http($url)
{
$disallowed = ['http://', 'https://'];
foreach ($disallowed as $d) {
if (strpos($url, $d) === 0) {
return str_replace($d, '', $url);
}
}
return $url;
}
}