<?php
namespace App\Auth;
use App\Entity\Customer;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
class TokenAuth
{
public function __construct(
private readonly RequestStack $requestStack,
private readonly EntityManagerInterface $entityManager,
) {
}
public function getCustomerByToken(): Customer
{
$token = $this->getToken();
if (!$token) {
throw new UnauthorizedHttpException('Not authorized');
}
/**
* @var Customer|null
*/
$customer = $this->entityManager->getRepository(Customer::class)->getCustomerByToken($token);
if (!$customer) {
throw new UnauthorizedHttpException('Not authorized');
}
return $customer;
}
private function getToken(): ?string
{
$request = $this->requestStack->getCurrentRequest();
return $request->get('AUTH_TOKEN');
}
}