<?php
namespace App\EventSubscriber\Api;
use App\Constant\EmailConfiguration;
use App\Constant\ErrorCode;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Lexik\Bundle\JWTAuthenticationBundle\Events as LexikEvents;
use Lexik\Bundle\JWTAuthenticationBundle\Event\JWTExpiredEvent;
use Lexik\Bundle\JWTAuthenticationBundle\Event\AuthenticationSuccessEvent;
use Lexik\Bundle\JWTAuthenticationBundle\Response\JWTAuthenticationSuccessResponse;
use Symfony\Component\HttpFoundation\RequestStack;
use Doctrine\ORM\EntityManagerInterface;
use App\AppEvents;
use Symfony\Component\HttpKernel\Event\TerminateEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Mime\Address;
use Symfony\Component\Mime\Email;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
use Symfony\Component\Security\Core\Exception\DisabledException;
use Symfony\Component\Mailer\MailerInterface;
class AuthenticatorSubscriber implements EventSubscriberInterface
{
private $request;
private $em;
private $parameterBag;
public function __construct(
RequestStack $requestStack,
EntityManagerInterface $em,
ParameterBagInterface $parameterBag,
MailerInterface $mailer,
EventDispatcherInterface $dispatcher)
{
$this->request = $requestStack->getCurrentRequest();
$this->em = $em;
$this->parameterBag = $parameterBag;
}
public function onAuthenticationSuccess(AuthenticationSuccessEvent $event)
{
$now = new \DateTime();
$ttl = $this->parameterBag->get('lexik_jwt_authentication.token_ttl');
$event->setData(array_merge($event->getData(), [
'life_time' => $ttl,
'expire' => $now->getTimestamp() + $ttl
]));
}
public function onAuthentificationExpired(JWTExpiredEvent $event)
{
$exception = $event->getException();
$reponse = $event->getResponse();
switch (get_class($exception)) {
case BadCredentialsException::class:
/// Badcredential
$reponse->setStatusCode(ErrorCode::JWT_BAD_CREDENTIAL);
$reponse->setMessage([
'en' => 'Username/Email or Password invalid!',
'fr' => 'Nom utilisateur/Email ou Mot de passe invalide!'
]);
break;
case DisabledException::class:
/// Compte desactiver pour licence ou autre cas
$reponse->setStatusCode(ErrorCode::DISABLED_ACCOUNT);
$reponse->setMessage([
'en' => 'User account is disabled.',
'fr' => 'Compte utilisateur désactivé.'
]);
break;
}
$event->setResponse($reponse);
}
public static function getSubscribedEvents()
{
return [
LexikEvents::JWT_EXPIRED => 'onAuthentificationExpired',
LexikEvents::AUTHENTICATION_SUCCESS => 'onAuthenticationSuccess',
];
}
}