<?php
namespace App\Listener;
use App\Repository\UserRepository;
use Lexik\Bundle\JWTAuthenticationBundle\Event\JWTCreatedEvent;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\RequestStack;
use DateInterval;
use App\Services\SqlService\SqlService;
class JWTCreatedListener extends AbstractController
{
private $requestStack;
private $userRepository;
private $sqlService;
/**
* @param RequestStack $requestStack
* @param UserRepository $userRepository
*/
public function __construct(RequestStack $requestStack, UserRepository $userRepository, SqlService $sqlService)
{
$this->requestStack = $requestStack;
$this->userRepository = $userRepository;
$this->sqlService = $sqlService;
}
/**
* @param JWTCreatedEvent $event
* @param UserRepository $userRepository
* @return void
* este se inicia el primero
*/
public function onJWTCreated(JWTCreatedEvent $event)
{
$payload = $event->getData();
$data = $this->userRepository->findOneByEmail($payload['username']);
// Fecha de expiracion del token 3 horas a partir de la ultima visita
$expiration = new \DateTime();
$expiration->add(new DateInterval('PT2H'));
$sql = "SELECT valor FROM custom_values
WHERE entidad = 'USER' AND entidad_id = ? AND clave = 'foto'";
// Solo se activa cuando se hace login //
$payload = $event->getData();
$payload['exp'] = $expiration->getTimestamp();
$payload['uuid'] = $data->getId();
$payload['username'] = $data->getEmail();
$payload['roles'] = $data->getRoles();
$payload['dni'] = $data->getDni();
$payload['nombre'] = $data->getNombre();
$payload['estado'] = $data->getEstado();
$foto = $this->sqlService->generateSql($sql, [$data->getId()]);
if ($foto) {
$payload['foto'] = $foto['valor'];
}
$event->setData($payload);
$header = $event->getHeader();
$header['cty'] = 'JWT';
$event->setHeader($header);
}
}