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