1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Damax\Bundle\ApiAuthBundle\Tests\Security\Jwt; |
6
|
|
|
|
7
|
|
|
use Damax\Bundle\ApiAuthBundle\Jwt\TokenBuilder; |
8
|
|
|
use Damax\Bundle\ApiAuthBundle\Security\JsonResponseFactory; |
9
|
|
|
use Damax\Bundle\ApiAuthBundle\Security\Jwt\AuthenticationHandler; |
10
|
|
|
use PHPUnit\Framework\MockObject\MockObject; |
11
|
|
|
use PHPUnit\Framework\TestCase; |
12
|
|
|
use Symfony\Component\HttpFoundation\Request; |
13
|
|
|
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken; |
14
|
|
|
use Symfony\Component\Security\Core\Exception\AuthenticationException; |
15
|
|
|
use Symfony\Component\Security\Core\Exception\UnsupportedUserException; |
16
|
|
|
use Symfony\Component\Security\Core\User\User; |
17
|
|
|
|
18
|
|
|
class AuthenticationHandlerTest extends TestCase |
19
|
|
|
{ |
20
|
|
|
/** |
21
|
|
|
* @var TokenBuilder|MockObject |
22
|
|
|
*/ |
23
|
|
|
private $builder; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* @var AuthenticationHandler |
27
|
|
|
*/ |
28
|
|
|
private $handler; |
29
|
|
|
|
30
|
|
|
protected function setUp() |
31
|
|
|
{ |
32
|
|
|
$this->builder = $this->createMock(TokenBuilder::class); |
33
|
|
|
$this->handler = new AuthenticationHandler($this->builder, new JsonResponseFactory()); |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* @test |
38
|
|
|
*/ |
39
|
|
|
public function it_handles_successful_request() |
40
|
|
|
{ |
41
|
|
|
$user = new User('[email protected]', 'qwerty'); |
42
|
|
|
|
43
|
|
|
$this->builder |
44
|
|
|
->expects($this->once()) |
45
|
|
|
->method('fromUser') |
46
|
|
|
->with($this->identicalTo($user)) |
47
|
|
|
->willReturn('XYZ') |
48
|
|
|
; |
49
|
|
|
|
50
|
|
|
$response = $this->handler->onAuthenticationSuccess(new Request(), new UsernamePasswordToken($user, 'qwerty', 'main')); |
51
|
|
|
|
52
|
|
|
$this->assertEquals(json_encode(['token' => 'XYZ']), $response->getContent()); |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
/** |
56
|
|
|
* @test |
57
|
|
|
*/ |
58
|
|
|
public function it_fails_to_handle_successful_request() |
59
|
|
|
{ |
60
|
|
|
$token = new UsernamePasswordToken('anon.', 'qwerty', 'main'); |
61
|
|
|
|
62
|
|
|
$this->expectException(UnsupportedUserException::class); |
63
|
|
|
|
64
|
|
|
$this->handler->onAuthenticationSuccess(new Request(), $token); |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
/** |
68
|
|
|
* @test |
69
|
|
|
*/ |
70
|
|
|
public function it_handles_failure_request() |
71
|
|
|
{ |
72
|
|
|
$response = $this->handler->onAuthenticationFailure(new Request(), new AuthenticationException('Invalid username.')); |
73
|
|
|
|
74
|
|
|
$this->assertEquals(401, $response->getStatusCode()); |
75
|
|
|
$this->assertEquals(json_encode(['error' => ['code' => 401, 'message' => 'Unauthorized']]), $response->getContent()); |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
|