|
1
|
|
|
<?php |
|
2
|
|
|
declare(strict_types = 1); |
|
3
|
|
|
/** |
|
4
|
|
|
* /src/EventSubscriber/AuthenticationFailureSubscriber.php |
|
5
|
|
|
* |
|
6
|
|
|
* @author TLe, Tarmo Leppänen <[email protected]> |
|
7
|
|
|
*/ |
|
8
|
|
|
|
|
9
|
|
|
namespace App\EventSubscriber; |
|
10
|
|
|
|
|
11
|
|
|
use App\Doctrine\DBAL\Types\EnumLogLoginType; |
|
12
|
|
|
use App\Repository\UserRepository; |
|
13
|
|
|
use App\Utils\LoginLogger; |
|
14
|
|
|
use Lexik\Bundle\JWTAuthenticationBundle\Event\AuthenticationFailureEvent; |
|
15
|
|
|
use Lexik\Bundle\JWTAuthenticationBundle\Events; |
|
16
|
|
|
use Symfony\Component\EventDispatcher\EventSubscriberInterface; |
|
17
|
|
|
use Throwable; |
|
18
|
|
|
|
|
19
|
|
|
/** |
|
20
|
|
|
* Class AuthenticationFailureSubscriber |
|
21
|
|
|
* |
|
22
|
|
|
* @package App\EventSubscriber |
|
23
|
|
|
* @author TLe, Tarmo Leppänen <[email protected]> |
|
24
|
|
|
*/ |
|
25
|
|
|
class AuthenticationFailureSubscriber implements EventSubscriberInterface |
|
26
|
|
|
{ |
|
27
|
5 |
|
public function __construct( |
|
28
|
|
|
private readonly LoginLogger $loginLogger, |
|
29
|
|
|
private readonly UserRepository $userRepository, |
|
30
|
|
|
) { |
|
31
|
5 |
|
} |
|
32
|
|
|
|
|
33
|
|
|
/** |
|
34
|
|
|
* {@inheritdoc} |
|
35
|
|
|
* |
|
36
|
|
|
* @return array<string, string> |
|
37
|
|
|
*/ |
|
38
|
1 |
|
public static function getSubscribedEvents(): array |
|
39
|
|
|
{ |
|
40
|
1 |
|
return [ |
|
41
|
1 |
|
AuthenticationFailureEvent::class => 'onAuthenticationFailure', |
|
42
|
1 |
|
Events::AUTHENTICATION_FAILURE => 'onAuthenticationFailure', |
|
43
|
1 |
|
]; |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
|
|
/** |
|
47
|
|
|
* Method to log login failures to database. |
|
48
|
|
|
* |
|
49
|
|
|
* This method is called when following event is broadcast; |
|
50
|
|
|
* - \Lexik\Bundle\JWTAuthenticationBundle\Events::AUTHENTICATION_FAILURE |
|
51
|
|
|
* |
|
52
|
|
|
* @throws Throwable |
|
53
|
|
|
*/ |
|
54
|
5 |
|
public function onAuthenticationFailure(AuthenticationFailureEvent $event): void |
|
55
|
|
|
{ |
|
56
|
5 |
|
$token = $event->getException()->getToken(); |
|
57
|
5 |
|
$user = $token?->getUser(); |
|
58
|
|
|
|
|
59
|
|
|
// Fetch user entity |
|
60
|
5 |
|
if ($token !== null && $user !== null) { |
|
61
|
2 |
|
$identifier = $user->getUserIdentifier(); |
|
62
|
|
|
|
|
63
|
2 |
|
$this->loginLogger->setUser($this->userRepository->loadUserByIdentifier($identifier, false)); |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
5 |
|
$this->loginLogger->process(EnumLogLoginType::TYPE_FAILURE); |
|
67
|
|
|
} |
|
68
|
|
|
} |
|
69
|
|
|
|