1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Damax\Bundle\ApiAuthBundle\Security\Jwt; |
6
|
|
|
|
7
|
|
|
use Damax\Bundle\ApiAuthBundle\Jwt\TokenBuilder; |
8
|
|
|
use Damax\Bundle\ApiAuthBundle\Security\ResponseFactory; |
9
|
|
|
use Symfony\Component\HttpFoundation\Request; |
10
|
|
|
use Symfony\Component\HttpFoundation\Response; |
11
|
|
|
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; |
12
|
|
|
use Symfony\Component\Security\Core\Exception\AuthenticationException; |
13
|
|
|
use Symfony\Component\Security\Core\Exception\UnsupportedUserException; |
14
|
|
|
use Symfony\Component\Security\Core\User\UserInterface; |
15
|
|
|
use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface; |
16
|
|
|
use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface; |
17
|
|
|
|
18
|
|
|
final class AuthenticationHandler implements AuthenticationSuccessHandlerInterface, AuthenticationFailureHandlerInterface |
19
|
|
|
{ |
20
|
|
|
private $builder; |
21
|
|
|
private $response; |
22
|
|
|
|
23
|
|
|
public function __construct(TokenBuilder $builder, ResponseFactory $response) |
24
|
|
|
{ |
25
|
|
|
$this->builder = $builder; |
26
|
|
|
$this->response = $response; |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
public function onAuthenticationSuccess(Request $request, TokenInterface $token): Response |
30
|
|
|
{ |
31
|
|
|
$user = $token->getUser(); |
32
|
|
|
|
33
|
|
|
if (!$user instanceof UserInterface) { |
34
|
|
|
throw new UnsupportedUserException('User not supported.'); |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
$jwtString = $this->builder->fromUser($user); |
38
|
|
|
|
39
|
|
|
return $this->response->fromToken($jwtString); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
public function onAuthenticationFailure(Request $request, AuthenticationException $exception): Response |
43
|
|
|
{ |
44
|
|
|
return $this->response->fromError(Response::HTTP_UNAUTHORIZED, $exception); |
45
|
|
|
} |
46
|
|
|
} |
47
|
|
|
|