src/Core/EventSubscriber/AuthorizationHeaderSubscriber.php line 52

  1. <?php
  2. declare(strict_types=1);
  3. /**
  4.  * Copyright (c) 2022 TECLA Consulting Group oü.
  5.  * All rights reserved.
  6.  *
  7.  * This unpublished material is proprietary to TECLA Consulting Group oü.
  8.  * All rights reserved. The methods and
  9.  * techniques described herein are considered trade secrets
  10.  * and/or confidential. Reproduction or distribution, in whole
  11.  * or in part, is forbidden except by express written permission
  12.  * of TECLA Consulting Group oü.
  13.  *
  14.  * @author    Matúš Sýkorjak <matus@tecla.no>
  15.  * @copyright 2022 TECLA Consulting Group oü
  16.  */
  17. namespace App\Core\EventSubscriber;
  18. use App\Contact\Model\Identity\ContactId;
  19. use App\Contact\Repository\ContactRepositoryInterface;
  20. use App\Contact\Security\ContactContextInterface;
  21. use JetBrains\PhpStorm\ArrayShape;
  22. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  23. use Symfony\Component\HttpKernel\Event\RequestEvent;
  24. use Symfony\Component\HttpKernel\KernelEvents;
  25. use Throwable;
  26. final class AuthorizationHeaderSubscriber implements EventSubscriberInterface
  27. {
  28.     private ContactRepositoryInterface $contactRepository;
  29.     private ContactContextInterface $contactContext;
  30.     public function __construct(ContactRepositoryInterface $contactRepositoryContactContextInterface $contactContext)
  31.     {
  32.         $this->contactRepository $contactRepository;
  33.         $this->contactContext $contactContext;
  34.     }
  35.     #[ArrayShape([KernelEvents::REQUEST => 'string'])]
  36.     public static function getSubscribedEvents(): array
  37.     {
  38.         return [
  39.             KernelEvents::REQUEST => [
  40.                 ['onKernelRequest'5],
  41.             ],
  42.         ];
  43.     }
  44.     public function onKernelRequest(RequestEvent $event): void
  45.     {
  46.         if (false === $event->isMainRequest()) {
  47.             return;
  48.         }
  49.         $request $event->getRequest();
  50.         if (false === $request->headers->has('Authorization')) {
  51.             return;
  52.         }
  53.         try {
  54.             $authorizationHeader explode(' '$request->headers->get('Authorization'));
  55.             [$username$password] = explode(':'base64_decode($authorizationHeader[1]));
  56.             $contactId ContactId::createFromString($username);
  57.             $contact $this->contactRepository->find($contactId);
  58.             $this->contactContext->setCurrent($contact);
  59.         } catch (Throwable $e) {
  60.         }
  61.     }
  62. }