<?php
declare(strict_types=1);
namespace App\EventSubscriber;
use JetBrains\PhpStorm\ArrayShape;
use Lexik\Bundle\JWTAuthenticationBundle\Event\AuthenticationFailureEvent;
use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use function json_decode;
final class AuthenticationFailedSubscriber implements EventSubscriberInterface
{
public function __construct(
private readonly LoggerInterface $logger,
)
{
}
#[ArrayShape(['lexik_jwt_authentication.on_authentication_failure' => "string"])]
public static function getSubscribedEvents(): array
{
return [
'lexik_jwt_authentication.on_authentication_failure' => 'onAuthenticationFailure',
];
}
public function onAuthenticationFailure(AuthenticationFailureEvent $event)
{
$content = json_decode($event->getRequest()->getContent(), true);
$username = $content['username'] ?? '';
$this->logger->error(
sprintf(
"The user \"%s\" was unable to login. Exception: \"%s\" Trace: %s",
$username,
$event->getException()->getMessage(),
$event->getException()->getTraceAsString(),
),
);
}
}