src/Auth/TokenAuth.php line 18

Open in your IDE?
  1. <?php
  2. namespace App\Auth;
  3. use App\Entity\Customer;
  4. use Doctrine\ORM\EntityManagerInterface;
  5. use Symfony\Component\HttpFoundation\RequestStack;
  6. use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
  7. class TokenAuth
  8. {
  9.     public function __construct(
  10.         private readonly RequestStack $requestStack,
  11.         private readonly EntityManagerInterface $entityManager,
  12.     ) {
  13.     }
  14.     public function getCustomerByToken(): Customer
  15.     {
  16.         $token $this->getToken();
  17.         if (!$token) {
  18.             throw new UnauthorizedHttpException('Not authorized');
  19.         }
  20.         /**
  21.          * @var Customer|null
  22.          */
  23.         $customer $this->entityManager->getRepository(Customer::class)->getCustomerByToken($token);
  24.         if (!$customer) {
  25.             throw new UnauthorizedHttpException('Not authorized');
  26.         }
  27.         return $customer;
  28.     }
  29.     private function getToken(): ?string
  30.     {
  31.         $request $this->requestStack->getCurrentRequest();
  32.         return $request->get('AUTH_TOKEN');
  33.     }
  34. }