1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
use PHPUnit\Framework\TestCase; |
4
|
|
|
use responsible\responsible; |
5
|
|
|
use responsible\core\auth; |
6
|
|
|
use responsible\core\headers; |
7
|
|
|
use responsible\core\exception; |
|
|
|
|
8
|
|
|
|
9
|
|
|
final class AuthTest extends TestCase |
10
|
|
|
{ |
11
|
|
|
private $options; |
12
|
|
|
|
13
|
|
|
private $requestTime; |
14
|
|
|
|
15
|
|
|
private const SECRET_KEY = 'mock-key'; |
16
|
|
|
|
17
|
|
|
private const TOKEN = 'abc-123'; |
18
|
|
|
|
19
|
|
|
public function setUp() |
20
|
|
|
{ |
21
|
|
|
$apiOptions = new options; |
22
|
|
|
$this->options = $apiOptions->getApiOptions(); |
23
|
|
|
$this->requestTime = $_SERVER['REQUEST_TIME']; |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* @test Test if JWT is valid |
28
|
|
|
*/ |
29
|
|
|
public function testJWTCanEncodeAndDecode(): void |
30
|
|
|
{ |
31
|
|
|
$jwt = new auth\jwt; |
32
|
|
|
|
33
|
|
|
$payload = [ |
34
|
|
|
'iss' => 'http://localhost', |
35
|
|
|
'iat' => $this->requestTime, |
36
|
|
|
'exp' => $this->requestTime, |
37
|
|
|
'nbf' => $this->requestTime, |
38
|
|
|
]; |
39
|
|
|
|
40
|
|
|
$encoded = $jwt->key(self::SECRET_KEY) |
41
|
|
|
->setOptions($this->options) |
42
|
|
|
->setPayload($payload) |
|
|
|
|
43
|
|
|
->encode($payload) |
|
|
|
|
44
|
|
|
; |
45
|
|
|
|
46
|
|
|
$this->assertEquals(true, is_string($encoded)); |
47
|
|
|
|
48
|
|
|
$decoded = $jwt |
49
|
|
|
->setOptions($this->options) |
50
|
|
|
->token($encoded) |
51
|
|
|
->key(self::SECRET_KEY) |
52
|
|
|
->decode() |
53
|
|
|
; |
54
|
|
|
|
55
|
|
|
$this->assertEquals(true, (is_array($decoded)&&!empty($decoded)) ); |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
/** |
59
|
|
|
* @test Test if JWT is not valid and throws an exception |
60
|
|
|
*/ |
61
|
|
|
public function testJWTIsNotValid(): void |
62
|
|
|
{ |
63
|
|
|
$jwt = new auth\jwt; |
64
|
|
|
|
65
|
|
|
$this->expectException(exception\errorException::class); |
66
|
|
|
|
67
|
|
|
$decoded = $jwt |
|
|
|
|
68
|
|
|
->setOptions($this->options) |
69
|
|
|
->token(self::TOKEN) |
70
|
|
|
->key(self::SECRET_KEY) |
71
|
|
|
->decode() |
72
|
|
|
; |
73
|
|
|
} |
74
|
|
|
} |
Let?s assume that you have a directory layout like this:
and let?s assume the following content of
Bar.php
:If both files
OtherDir/Foo.php
andSomeDir/Foo.php
are loaded in the same runtime, you will see a PHP error such as the following:PHP Fatal error: Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php
However, as
OtherDir/Foo.php
does not necessarily have to be loaded and the error is only triggered if it is loaded beforeOtherDir/Bar.php
, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias: