Issues (13)

src/EventSubscriber/SecuritySubscriber.php (1 issue)

1
<?php
2
3
namespace App\EventSubscriber;
4
5
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
6
use Symfony\Component\Security\Core\AuthenticationEvents;
7
use Symfony\Component\Security\Core\Event\AuthenticationFailureEvent;
8
use Symfony\Component\Security\Core\Event\AuthenticationEvent;
9
use Psr\Log\LoggerInterface;
10
11
12
/**
13
 * This event subscriber monitors and logs user authentication attempts.
14
 *
15
 */
16
class SecuritySubscriber implements EventSubscriberInterface
17
{
18
    public static function getSubscribedEvents()
19
    {
20
        return array(
21
            AuthenticationEvents::AUTHENTICATION_FAILURE => 'onAuthenticationFailure',
22
            AuthenticationEvents::AUTHENTICATION_SUCCESS => 'onAuthenticationSuccess',
23
        );
24
    }
25
26
    public function __construct(LoggerInterface $logger)
27
    {
28
        $this->logger = $logger;
0 ignored issues
show
Bug Best Practice introduced by
The property logger does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
29
    }
30
31
    public function onAuthenticationFailure(AuthenticationFailureEvent $event)
32
    {
33
        $exception = $event->getAuthenticationException();
34
        $token = $event->getAuthenticationToken();
35
        $creds = $token->getCredentials();
36
        $this->logger->error("Login failed for " . $creds['username'] . ": " . $exception->getMessage());
37
    }
38
39
    public function onAuthenticationSuccess(AuthenticationEvent $event)
40
    {
41
        $token = $event->getAuthenticationToken();
42
        if ($token->getUsername() != "anon.") {
43
            $this->logger->info("Login succeeded: " . $token->getUsername());
44
        }
45
    }
46
}
47