<?php
namespace App\EventListener;
use App\Repository\ClienteRepository;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
readonly class ApiTokenListener
{
public function __construct(private ClienteRepository $clienteRepository)
{
}
public function onKernelRequest(RequestEvent $event): void
{
$request = $event->getRequest();
if (!str_starts_with($request->getPathInfo(), '/api/') || str_starts_with($request->getPathInfo(), '/api/doc')) {
return;
}
$authHeader = $request->headers->get('Authorization');
if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
throw new AccessDeniedHttpException('Missing or invalid Authorization header.');
}
$token = substr($authHeader, 7);
$cliente = $this->clienteRepository->findOneBy(['token' => $token]);
if (!$cliente) {
throw new AccessDeniedHttpException('Invalid API token.');
}
$request->attributes->set('cliente', $cliente);
}
}