UserAutoLogon   A
last analyzed

Complexity

Total Complexity 3

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 3
eloc 17
dl 0
loc 47
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A autoLogon() 0 12 2
1
<?php
2
3
namespace App\Security;
4
5
use App\Entity\User;
6
use Exception;
7
use Symfony\Component\EventDispatcher\Event;
8
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
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
     * @return Event
47
     * Auto Logs on the passed user
48
     * @throws Exception
49
     */
50
    public function autoLogon(User $user): Event
51
    {
52
        $request = $this->requestStack->getCurrentRequest();
53
        if($request === null){
54
            throw new Exception('request is null');
55
        }
56
        //Login user
57
        $token = new UsernamePasswordToken($user, null, 'main', $user->getRoles());
58
        $this->tokenStorage->setToken($token);
59
        $this->session->set('_security_main', serialize($token));
60
        $event = new InteractiveLoginEvent($request, $token);
61
        return $this->dispatcher->dispatch("security.interactive_login", $event);
62
    }
63
}