<?php
namespace App\EventSubscriber;
use App\Controller\API\TokenAuthenticatedController;
use App\Services\UserService;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Finder\Exception\AccessDeniedException;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Contracts\Translation\TranslatorInterface;
class TokenSubscriber implements EventSubscriberInterface
{
private $userService;
private $translator;
/**
* @param UserService $userService
* @param TranslatorInterface $translator
*/
public function __construct(UserService $userService, TranslatorInterface $translator)
{
$this->userService = $userService;
$this->translator = $translator;
}
public function onKernelController(ControllerEvent $event)
{
$controller = $event->getController();
if (is_array($controller)) {
$controller = $controller[0];
}
if ($controller instanceof TokenAuthenticatedController) {
$token = $event->getRequest()->headers->get('secret-token');
if (!$token) {
throw new AccessDeniedException(
$this->translator->trans('app.api.forbidden.text',
[],
null,
$event->getRequest()->getLocale())
);
}
$user = $this->userService->findByToken($token);
if (!$user) {
throw new AccessDeniedException(
$this->translator->trans('app.api.forbidden.text',
[],
null,
$event->getRequest()->getLocale())
);
}
}
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::CONTROLLER => 'onKernelController'
];
}
}