<?php
namespace App\Security;
use App\Entity\Config;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
class ApiAuthenticator implements EventSubscriberInterface
{
private $em;
private $client;
public function __construct(EntityManagerInterface $em, HttpClientInterface $client)
{
$this->em = $em;
$this->client = $client;
}
public function authenticate(Request $request)
{
}
public static function getSubscribedEvents(): array
{
return [KernelEvents::REQUEST => ['onKernelRequest', 128]];
}
/**
* @throws TransportExceptionInterface
*/
public function onKernelRequest(RequestEvent $event): void
{
$request = $event->getRequest();
if(str_starts_with($request->getRequestUri(),'/api')) {
if (!($request->headers->has('Authorization') && 0 === strpos($request->headers->get('Authorization'), 'Bearer '))) {
$event->setResponse(new Response('Unauthorized.', 401));
}
$authorization = $request->headers->get('Authorization');
$apiToken = substr($authorization, 7);
$options['auth_bearer'] = $apiToken;
/** @var Config $config */
$config = $this->em->getRepository(Config::class)->findOne();
$response = $this->client->request(
'GET',
$config->getEventUrl(),
$options
);
if(!($response->getStatusCode() ===200)){
$event->setResponse(new Response('Unauthorized.', 401));
}
}
}
}