1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Piotzkhider\FirebaseAuthenticationModule\Guard; |
6
|
|
|
|
7
|
|
|
use Aura\Web\Request; |
8
|
|
|
use BEAR\Resource\ResourceObject; |
9
|
|
|
use Koriym\HttpConstants\ResponseHeader; |
10
|
|
|
use Koriym\HttpConstants\StatusCode; |
11
|
|
|
use Kreait\Firebase\Auth\UserRecord; |
12
|
|
|
use Lcobucci\JWT\Token; |
13
|
|
|
use Piotzkhider\FirebaseAuthenticationModule\AuthInterface; |
14
|
|
|
use Piotzkhider\FirebaseAuthenticationModule\Exception\AuthenticationException; |
15
|
|
|
use Piotzkhider\FirebaseAuthenticationModule\Exception\InvalidToken; |
16
|
|
|
use Piotzkhider\FirebaseAuthenticationModule\Exception\TokenNotFound; |
17
|
|
|
use Piotzkhider\FirebaseAuthenticationModule\Extractor\TokenExtractorResolver; |
18
|
|
|
|
19
|
|
|
class Authenticator implements AuthenticatorInterface |
20
|
|
|
{ |
21
|
|
|
/** |
22
|
|
|
* @var AuthInterface |
23
|
|
|
*/ |
24
|
|
|
private $auth; |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* @var TokenExtractorResolver |
28
|
|
|
*/ |
29
|
|
|
private $resolver; |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* @var UserRecord |
33
|
|
|
*/ |
34
|
|
|
private $user; |
35
|
|
|
|
36
|
4 |
|
public function __construct(AuthInterface $auth, TokenExtractorResolver $resolver) |
37
|
|
|
{ |
38
|
4 |
|
$this->auth = $auth; |
39
|
4 |
|
$this->resolver = $resolver; |
40
|
4 |
|
} |
41
|
|
|
|
42
|
1 |
|
public function getCredentials(Request $request): Token |
43
|
|
|
{ |
44
|
1 |
|
$extractor = $this->resolver->resolve($request); |
45
|
1 |
|
$idToken = $extractor->extract($request); |
46
|
|
|
|
47
|
1 |
|
return $this->auth->verifyIdToken($idToken); |
48
|
|
|
} |
49
|
|
|
|
50
|
1 |
|
public function getUser(Token $token): UserRecord |
51
|
|
|
{ |
52
|
1 |
|
if ($this->user !== null) { |
53
|
|
|
return $this->user; |
54
|
|
|
} |
55
|
|
|
|
56
|
1 |
|
$uidClaim = $token->getClaim('sub'); |
57
|
|
|
|
58
|
1 |
|
return $this->user = $this->auth->getUser($uidClaim); |
59
|
|
|
} |
60
|
|
|
|
61
|
1 |
|
public function onAuthenticationFailure(ResourceObject $ro, AuthenticationException $e): ResourceObject |
62
|
|
|
{ |
63
|
1 |
|
if ($e instanceof TokenNotFound) { |
64
|
1 |
|
$ro->code = StatusCode::UNAUTHORIZED; |
65
|
1 |
|
$ro->headers[ResponseHeader::WWW_AUTHENTICATE] = sprintf( |
66
|
1 |
|
'Bearer realm="token_required",error="token_not_found",error_description="%s"', |
67
|
1 |
|
$e->getMessage() |
68
|
|
|
); |
69
|
|
|
|
70
|
1 |
|
return $ro; |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
if ($e instanceof InvalidToken) { |
74
|
|
|
$ro->code = StatusCode::UNAUTHORIZED; |
75
|
|
|
$ro->headers[ResponseHeader::WWW_AUTHENTICATE] = sprintf( |
76
|
|
|
'Bearer realm="token_required",error="invalid_token",error_description="%s"', |
77
|
|
|
$e->getMessage() |
78
|
|
|
); |
79
|
|
|
|
80
|
|
|
return $ro; |
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
throw $e; |
84
|
|
|
} |
85
|
|
|
} |
86
|
|
|
|