src/Security/ApiAuthenticator.php line 37

Open in your IDE?
  1. <?php
  2. namespace App\Security;
  3. use App\Entity\Config;
  4. use Doctrine\ORM\EntityManagerInterface;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use Symfony\Component\HttpFoundation\Request;
  7. use Symfony\Component\HttpFoundation\Response;
  8. use Symfony\Component\HttpKernel\Event\RequestEvent;
  9. use Symfony\Component\HttpKernel\KernelEvents;
  10. use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
  11. use Symfony\Contracts\HttpClient\HttpClientInterface;
  12. class ApiAuthenticator implements EventSubscriberInterface
  13. {
  14.     private $em;
  15.     private $client;
  16.     public function __construct(EntityManagerInterface $emHttpClientInterface $client)
  17.     {
  18.         $this->em $em;
  19.         $this->client $client;
  20.     }
  21.     public static function getSubscribedEvents(): array
  22.     {
  23.         return [KernelEvents::REQUEST => ['onKernelRequest'128]];
  24.     }
  25.     /**
  26.      * @throws TransportExceptionInterface
  27.      */
  28.     public function onKernelRequest(RequestEvent $event)
  29.     {
  30.         $headers apache_request_headers();
  31.         $request $event->getRequest();
  32.         if(str_starts_with($request->getRequestUri(),'/api')) {
  33.             $authorization = !empty($headers['Authorization'])?$headers['Authorization']:($request->headers->has('Authorization') && $request->headers->get('Authorization') ?$request->headers->get('Authorization'):null);
  34.             if(strpos($authorization'Bearer ') >=0) {
  35.                 $apiToken substr($authorization7);
  36.                 $options['auth_bearer'] = $apiToken;
  37.                 /** @var Config $config */
  38.                 $config $this->em->getRepository(Config::class)->findOne();
  39.                 $url $config->getUrl();
  40.                 $url str_replace('checkin'''$url).'events';
  41.                 $response $this->client->request(
  42.                     'GET',
  43.                     $url,
  44.                     $options
  45.                 );
  46.                 if(!($response->getStatusCode() ===200)){
  47.                     $event->setResponse(new Response('Unauthorized.'401));
  48.                 }
  49.             } else {
  50.                 $event->setResponse(new Response('Unauthorized.'401));
  51.             }
  52.         }
  53.     }
  54. }