Completed
Push — master ( 9305d9...d34e55 )
by Tarmo
46:41
created

Auth::getAuthorizationHeadersForUser()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 2
dl 0
loc 10
ccs 5
cts 5
cp 1
crap 2
rs 9.4285
c 0
b 0
f 0
1
<?php
2
declare(strict_types = 1);
3
/**
4
 * /src/Utils/Tests/Auth.php
5
 *
6
 * @author  TLe, Tarmo Leppänen <[email protected]>
7
 */
8
namespace App\Utils\Tests;
9
10
use App\Utils\JSON;
11
use Symfony\Component\DependencyInjection\ContainerInterface;
12
use Symfony\Component\HttpFoundation\Response;
13
14
/**
15
 * Class Auth
16
 *
17
 * @package App\Utils\Tests
18
 * @author  TLe, Tarmo Leppänen <[email protected]>
19
 */
20
class Auth
21
{
22
    /**
23
     * @var ContainerInterface
24
     */
25
    private $container;
26
27
    /**
28
     * JWT cache
29
     *
30
     * @var \string[]
31
     */
32
    private $cache = [];
33
34
    /**
35
     * Auth constructor.
36
     *
37
     * @param ContainerInterface $container
38
     */
39
    public function __construct(ContainerInterface $container)
40
    {
41
        $this->container = $container;
42
    }
43
44
    /**
45
     * Method to get authorization headers for specified user.
46
     *
47
     * @param string $username
48
     * @param string $password
49
     *
50
     * @return array
51
     *
52
     * @throws \Exception
53
     */
54
    public function getAuthorizationHeadersForUser(string $username, string $password): array
55
    {
56
        $key = \hash('sha512', $username . $password);
57
58
        if (!\array_key_exists($key, $this->cache)) {
59
            $this->cache[$key] = $this->getToken($username, $password);
60
        }
61
62
        // Return valid authorization headers for user
63
        return $this->getAuthorizationHeaders($this->cache[$key]);
64
    }
65
66
    /**
67
     * Method to get authorization headers for specified token.
68
     *
69
     * @param string $token
70
     *
71
     * @return array
72
     */
73
    public function getAuthorizationHeaders(string $token): array
74
    {
75
        return [
76
            'CONTENT_TYPE'          => 'application/json',
77
            'HTTP_AUTHORIZATION'    => 'Bearer ' . $token
78
        ];
79
    }
80
81
    /**
82
     * @return array
83
     */
84
    public function getJwtHeaders(): array
85
    {
86
        return [
87
            'REMOTE_ADDR'       => '123.123.123.123',
88
            'HTTP_USER_AGENT'   => 'foobar',
89
        ];
90
    }
91
92
    /**
93
     * Method to make actual login to application with specified username and password.
94
     *
95
     * @codeCoverageIgnore
96
     *
97
     * @param string $username
98
     * @param string $password
99
     *
100
     * @return string
101
     *
102
     * @throws \UnexpectedValueException
103
     */
104
    private function getToken(string $username, string $password): string
105
    {
106
        // Get client
107
        /** @noinspection MissingService */
108
        $client = $this->container->get('test.client');
109
110
        // Create request to make login using given credentials
111
        $client->request(
112
            'POST',
113
            '/auth/getToken',
114
            [],
115
            [],
116
            \array_merge(
117
                $this->getJwtHeaders(),
118
                [
119
                    'CONTENT_TYPE'          => 'application/json',
120
                    'HTTP_X-Requested-With' => 'XMLHttpRequest'
121
                ]
122
            ),
123
            \json_encode(['username' => $username, 'password' => $password])
124
        );
125
126
        /** @var Response $response */
127
        $response = $client->getResponse();
128
129
        if ($response === null) {
130
            throw new \UnexpectedValueException('Test client did not return response at all');
131
        }
132
133
        if ($response->getStatusCode() !== 200) {
134
            throw new \UnexpectedValueException('Invalid status code: '. $response->getStatusCode());
135
        }
136
137
        return JSON::decode($response->getContent())->token;
138
    }
139
}
140