<?php
declare(strict_types=1);
namespace Serglobin\ChatGptBundle\EventSubscriber;
use Serglobin\ChatGptBundle\Security\ChatGptVoter;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Core\Security;
class OpenAIApiSubscriber implements EventSubscriberInterface
{
public function __construct(private readonly Security $security)
{
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::REQUEST => 'onKernelRequest',
];
}
public function onKernelRequest(RequestEvent $requestEvent): void
{
$request = $requestEvent->getRequest();
$path = $request->getPathInfo();
if (\str_starts_with($path, '/api/openai') && !$this->security->isGranted(ChatGptVoter::VOTER_ATTRIBUTE)) {
$accessDeniedException = new AccessDeniedException();
$accessDeniedException->setAttributes(ChatGptVoter::VOTER_ATTRIBUTE);
throw $accessDeniedException;
}
}
}