1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace App\Security; |
4
|
|
|
|
5
|
|
|
use App\Entity\User; |
6
|
|
|
use Symfony\Component\EventDispatcher\Event; |
7
|
|
|
use Symfony\Component\EventDispatcher\EventDispatcherInterface; |
8
|
|
|
use Symfony\Component\HttpFoundation\Request; |
9
|
|
|
use Symfony\Component\HttpFoundation\RequestStack; |
10
|
|
|
use Symfony\Component\HttpFoundation\Session\SessionInterface; |
11
|
|
|
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; |
12
|
|
|
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken; |
13
|
|
|
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent; |
14
|
|
|
|
15
|
|
|
class UserAutoLogon |
16
|
|
|
{ |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* @var EventDispatcherInterface |
20
|
|
|
*/ |
21
|
|
|
private $dispatcher; |
22
|
|
|
/** |
23
|
|
|
* @var TokenStorageInterface |
24
|
|
|
*/ |
25
|
|
|
private $tokenStorage; |
26
|
|
|
/** |
27
|
|
|
* @var SessionInterface |
28
|
|
|
*/ |
29
|
|
|
private $session; |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* @var RequestStack |
33
|
|
|
*/ |
34
|
|
|
private $requestStack; |
35
|
|
|
|
36
|
|
|
public function __construct(EventDispatcherInterface $dispatcher, TokenStorageInterface $tokenStorage, SessionInterface $session, RequestStack $requestStack) |
37
|
|
|
{ |
38
|
|
|
$this->dispatcher = $dispatcher; |
39
|
|
|
$this->tokenStorage = $tokenStorage; |
40
|
|
|
$this->session = $session; |
41
|
|
|
$this->requestStack = $requestStack; |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
/** |
45
|
|
|
* @param User $user |
46
|
|
|
* @param Request $request |
47
|
|
|
* @return Event |
48
|
|
|
* Auto Logges on the passed user |
49
|
|
|
* |
50
|
|
|
*/ |
51
|
|
|
public function autoLogon(User $user): Event |
52
|
|
|
{ |
53
|
|
|
$request = $this->requestStack->getCurrentRequest(); |
54
|
|
|
//Login user |
55
|
|
|
$token = new UsernamePasswordToken($user, null, 'main', $user->getRoles()); |
56
|
|
|
$this->tokenStorage->setToken($token); |
57
|
|
|
$this->session->set('_security_main', serialize($token)); |
58
|
|
|
$event = new InteractiveLoginEvent($request, $token); |
|
|
|
|
59
|
|
|
return $this->dispatcher->dispatch("security.interactive_login", $event); |
60
|
|
|
} |
61
|
|
|
} |