<?php
declare(strict_types=1);
namespace Redatum\User\EventSubscriber;
use Lexik\Bundle\JWTAuthenticationBundle\Event\AuthenticationFailureEvent;
use Lexik\Bundle\JWTAuthenticationBundle\Event\AuthenticationSuccessEvent;
use Lexik\Bundle\JWTAuthenticationBundle\Event\JWTExpiredEvent;
use Lexik\Bundle\JWTAuthenticationBundle\Event\JWTInvalidEvent;
use Lexik\Bundle\JWTAuthenticationBundle\Event\JWTNotFoundEvent;
use Lexik\Bundle\JWTAuthenticationBundle\Events;
use Redatum\User\ApiResources\Mapper\UserInfoResourceMapper;
use Redatum\User\Entity\User;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use VisualCraft\RestBaseBundle\Problem\ProblemResponseFactory;
class AuthEventsSubscriber implements EventSubscriberInterface
{
private ProblemResponseFactory $problemResponseFactory;
private NormalizerInterface $normalizer;
private UserInfoResourceMapper $userShortInfoResourceFactory;
public function __construct(
ProblemResponseFactory $problemResponseFactory,
NormalizerInterface $normalizer,
UserInfoResourceMapper $userShortInfoResourceFactory
) {
$this->problemResponseFactory = $problemResponseFactory;
$this->normalizer = $normalizer;
$this->userShortInfoResourceFactory = $userShortInfoResourceFactory;
}
public static function getSubscribedEvents(): array
{
return [
Events::AUTHENTICATION_FAILURE => [
['processAuthenticationFailure'],
],
Events::AUTHENTICATION_SUCCESS => [
['processAuthenticationSuccess'],
],
Events::JWT_INVALID => [
['processJwtInvalid'],
],
Events::JWT_NOT_FOUND => [
['processJwtNotFound'],
],
Events::JWT_EXPIRED => [
['processJwtExpired'],
],
];
}
public function processAuthenticationFailure(AuthenticationFailureEvent $event): void
{
$exception = $event->getException();
$event->setResponse($this->problemResponseFactory->create($exception));
}
public function processAuthenticationSuccess(AuthenticationSuccessEvent $event): void
{
$user = $event->getUser();
if (!$user instanceof User) {
return;
}
$data = $event->getData();
$userResource = $this->userShortInfoResourceFactory->create($user);
$data['data'] = $this->normalizer->normalize($userResource, 'json');
$event->setData($data);
}
public function processJwtInvalid(JWTInvalidEvent $event): void
{
$exception = $event->getException();
$event->setResponse($this->problemResponseFactory->create($exception));
}
public function processJwtNotFound(JWTNotFoundEvent $event): void
{
$exception = $event->getException();
$event->setResponse($this->problemResponseFactory->create($exception));
}
public function processJwtExpired(JWTExpiredEvent $event): void
{
$exception = $event->getException();
$event->setResponse($this->problemResponseFactory->create($exception));
}
}