Completed
Push — api ( cecea0...116a36 )
by Kamil
29:57 queued 30s
created

ApiSecurityService::restoreToken()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
c 0
b 0
f 0
rs 10
cc 1
nc 1
nop 1
1
<?php
2
3
/*
4
 * This file is part of the Sylius package.
5
 *
6
 * (c) Paweł Jędrzejewski
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace Sylius\Behat\Service;
15
16
use Lexik\Bundle\JWTAuthenticationBundle\Security\Authentication\Token\JWTUserToken;
17
use Sylius\Behat\Service\Setter\CookieSetterInterface;
18
use Sylius\Component\User\Model\UserInterface;
19
use Symfony\Component\BrowserKit\AbstractBrowser;
20
use Symfony\Component\HttpFoundation\Session\SessionInterface;
21
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
22
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
23
use Symfony\Component\Security\Core\Exception\TokenNotFoundException;
24
25
final class ApiSecurityService implements SecurityServiceInterface
26
{
27
    /** @var AbstractBrowser */
28
    private $client;
29
30
    /** @var SharedStorageInterface */
31
    private $sharedStorage;
32
33
    public function __construct(AbstractBrowser $client, SharedStorageInterface $sharedStorage)
34
    {
35
        $this->client = $client;
36
        $this->sharedStorage = $sharedStorage;
37
    }
38
39
    public function logIn(UserInterface $user): void
40
    {
41
        $this->client->request(
42
            'POST',
43
            '/new-api/authentication-token',
44
            [],
45
            [],
46
            ['CONTENT_TYPE' => 'application/json', 'HTTP_ACCEPT' => 'application/json'],
47
            json_encode(['email' => $user->getEmail(), 'password' => 'sylius'])
48
        );
49
50
        $token = json_decode($this->client->getResponse()->getContent(), true)['token'];
51
52
        $this->sharedStorage->set('token', $token);
53
    }
54
55
    public function logOut(): void
56
    {
57
        $this->sharedStorage->set('token', null);
58
    }
59
60
    public function getCurrentToken(): TokenInterface
61
    {
62
        $token = new JWTUserToken();
63
        $token->setRawToken($this->sharedStorage->get('token'));
64
65
        return $token;
66
    }
67
68
    public function restoreToken(TokenInterface $token): void
69
    {
70
        $this->sharedStorage->set('token', (string) $token);
71
    }
72
}
73