<?php
declare(strict_types=1);
namespace App\EventListener;
use App\Entity\User;
use DateTimeImmutable;
use Doctrine\ORM\EntityManagerInterface;
use Lexik\Bundle\JWTAuthenticationBundle\Event\AuthenticationSuccessEvent;
use Lexik\Bundle\JWTAuthenticationBundle\Event\JWTCreatedEvent;
use phpDocumentor\Reflection\Types\This;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Csrf\TokenGenerator\TokenGeneratorInterface;
use Symfony\Component\Serializer\SerializerInterface;
class AuthenticationSuccessListener
{
/**
* @var SerializerInterface
*/
private $serializer;
/**
* AuthenticationSuccessListener constructor.
* @param SerializerInterface $serializer
*/
public function __construct(SerializerInterface $serializer)
{
$this->serializer = $serializer;
}
/**
* @param AuthenticationSuccessEvent $event
* @return void
*/
public function onAuthenticationSuccessResponse(AuthenticationSuccessEvent $event)
{
$data = $event->getData();
$user = $event->getUser();
if (!$user instanceof User) {
return;
}
$user = $this->serializer->serialize($user, 'json', ['groups' => 'user:read']);
$event->setData([
'status' => $event->getResponse()->getStatusCode(),
'message' => 'User authenticated succesfully.',
'token' => $data['token'],
'user' => json_decode($user)
]);
}
}