Passed
Push — issue#767 ( 902b86...e6d68a )
by Guilherme
05:21
created

SessionState::getClient()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
ccs 2
cts 2
cp 1
crap 1
1
<?php
2
/**
3
 * This file is part of the login-cidadao project or it's bundles.
4
 *
5
 * (c) Guilherme Donato <guilhermednt on github>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace LoginCidadao\OpenIDBundle\Storage;
12
13
use LoginCidadao\OAuthBundle\Model\ClientInterface;
14
use LoginCidadao\OpenIDBundle\Manager\ClientManager;
15
use Symfony\Component\HttpFoundation\Cookie;
16
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
17
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
18
19
class SessionState
20
{
21
    /** @var ClientManager */
22
    private $clientManager;
23
24
    /** @var TokenStorageInterface */
25
    protected $tokenStorage;
26
27 3
    public function __construct(ClientManager $clientManager, TokenStorageInterface $tokenStorage)
28
    {
29 3
        $this->clientManager = $clientManager;
30 3
        $this->tokenStorage = $tokenStorage;
31 3
    }
32
33 1
    public function getSessionState($client_id, $sessionId)
34
    {
35 1
        $client = $this->getClient($client_id);
36
37 1
        $url = $client->getMetadata()->getClientUri();
38 1
        $salt = bin2hex(random_bytes(15));
39
40 1
        $state = $client_id.$url.$sessionId.$salt;
41
42 1
        return hash('sha256', $state).".$salt";
43
    }
44
45 2
    public function getSessionId()
46
    {
47 2
        $token = $this->tokenStorage->getToken();
48 2
        if ($token !== null) {
49 1
            return hash('sha256', $token->serialize());
50
        } else {
51 1
            return '';
52
        }
53
    }
54
55
    /**
56
     * @param string $client_id
57
     * @return ClientInterface
58
     */
59 1
    private function getClient($client_id)
60
    {
61 1
        return $this->clientManager->getClientById($client_id);
62
    }
63
64 2
    public function onKernelResponse(FilterResponseEvent $event)
65
    {
66 2
        if ($event->isMasterRequest()) {
67 2
            $sessionId = $this->getSessionId();
68 2
            if ($sessionId !== '') {
69 1
                $cookie = new Cookie('session_state', $sessionId, 0, '/', null, false, false);
70 1
                $event->getResponse()->headers->setCookie($cookie);
71
            } else {
72 1
                $event->getResponse()->headers->removeCookie('session_state');
73
            }
74
        }
75 2
    }
76
}
77