1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Application\EventListener; |
4
|
|
|
|
5
|
|
|
use Application\Entity\UserActionEntity; |
6
|
|
|
use Symfony\Component\Security\Core\AuthenticationEvents; |
7
|
|
|
use Symfony\Component\EventDispatcher\EventSubscriberInterface; |
8
|
|
|
use Silex\Application; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* @author Borut Balažek <[email protected]> |
12
|
|
|
*/ |
13
|
|
|
class AuthenticationEventsListener implements EventSubscriberInterface |
14
|
|
|
{ |
15
|
|
|
protected $app; |
16
|
|
|
|
17
|
|
|
public function __construct(Application $app) |
18
|
|
|
{ |
19
|
|
|
$this->app = $app; |
20
|
|
|
} |
21
|
|
|
|
22
|
|
|
public function onAuthenticationSuccess($event) |
23
|
|
|
{ |
24
|
|
|
$app = $this->app; |
25
|
|
|
|
26
|
|
|
$user = $event->getAuthenticationToken()->getUser(); |
27
|
|
|
$user |
28
|
|
|
->setTimeLastActive(new \DateTime()) |
29
|
|
|
; |
30
|
|
|
|
31
|
|
|
$app['orm.em']->persist($user); |
32
|
|
|
$app['orm.em']->flush(); |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
public function onAuthenticationFailure($event) |
36
|
|
|
{ |
37
|
|
|
$app = $this->app; |
38
|
|
|
|
39
|
|
|
$authenticationToken = $event->getAuthenticationToken(); |
40
|
|
|
$user = $app['user.provider']->loadUserByUsername( |
41
|
|
|
$authenticationToken->getUser(), |
42
|
|
|
false |
43
|
|
|
); |
44
|
|
|
|
45
|
|
|
$userActionEntity = new UserActionEntity(); |
46
|
|
|
$userActionEntity |
47
|
|
|
->setUser($user) |
48
|
|
|
->setKey('user.login.fail') |
49
|
|
|
->setType('event') |
50
|
|
|
->setMessage('An user has tried to log in!') |
51
|
|
|
->setData(array( |
52
|
|
|
'username' => $authenticationToken->getUser(), |
53
|
|
|
)) |
54
|
|
|
->setIp($app['request']->getClientIp()) |
55
|
|
|
->setUserAgent($app['request']->headers->get('User-Agent')) |
56
|
|
|
; |
57
|
|
|
|
58
|
|
|
if (!$user) { |
59
|
|
|
$userActionEntity |
60
|
|
|
->setData( |
61
|
|
|
array( |
62
|
|
|
'username' => $app['request']->request->get('username'), |
63
|
|
|
) |
64
|
|
|
) |
65
|
|
|
; |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
$app['orm.em']->persist($userActionEntity); |
69
|
|
|
|
70
|
|
|
$app['orm.em']->flush(); |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
public static function getSubscribedEvents() |
74
|
|
|
{ |
75
|
|
|
return array( |
76
|
|
|
AuthenticationEvents::AUTHENTICATION_SUCCESS => array('onAuthenticationSuccess'), |
77
|
|
|
AuthenticationEvents::AUTHENTICATION_FAILURE => array('onAuthenticationFailure'), |
78
|
|
|
); |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|