<?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 static function getSubscribedEvents(): array
{
return [KernelEvents::REQUEST => ['onKernelRequest', 128]];
}
/**
* @throws TransportExceptionInterface
*/
public function onKernelRequest(RequestEvent $event)
{
$headers = apache_request_headers();
$request = $event->getRequest();
if(str_starts_with($request->getRequestUri(),'/api')) {
$authorization = !empty($headers['Authorization'])?$headers['Authorization']:($request->headers->has('Authorization') && $request->headers->get('Authorization') ?$request->headers->get('Authorization'):null);
if(strpos($authorization, 'Bearer ') >=0) {
$apiToken = substr($authorization, 7);
$options['auth_bearer'] = $apiToken;
/** @var Config $config */
$config = $this->em->getRepository(Config::class)->findOne();
$url = $config->getUrl();
$url = str_replace('checkin', '', $url).'events';
$response = $this->client->request(
'GET',
$url,
$options
);
if(!($response->getStatusCode() ===200)){
$event->setResponse(new Response('Unauthorized.', 401));
}
} else {
$event->setResponse(new Response('Unauthorized.', 401));
}
}
}
}