Completed
Push — master ( 3e3c14...4d1811 )
by yoshihiro
01:20
created

Authenticator::onAuthenticationFailure()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 24

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 4.125

Importance

Changes 0
Metric Value
dl 0
loc 24
ccs 7
cts 14
cp 0.5
rs 9.536
c 0
b 0
f 0
cc 3
nc 3
nop 2
crap 4.125
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 5
    public function __construct(AuthInterface $auth, TokenExtractorResolver $resolver)
32
    {
33 5
        $this->auth = $auth;
34 5
        $this->resolver = $resolver;
35 5
    }
36
37 1
    public function getCredentials(Request $request): Token
38
    {
39 1
        $extractor = $this->resolver->resolve($request);
40 1
        $idToken = $extractor->extract($request);
41
42 1
        return $this->auth->verifyIdToken($idToken);
43
    }
44
45 1
    public function getUser(Token $token): UserRecord
46
    {
47 1
        $uidClaim = $token->getClaim('sub');
48
49 1
        return $this->auth->getUser($uidClaim);
50
    }
51
52 1
    public function onAuthenticationFailure(ResourceObject $ro, AuthenticationException $e): ResourceObject
53
    {
54 1
        if ($e instanceof TokenNotFound) {
55 1
            $ro->code = StatusCode::UNAUTHORIZED;
56 1
            $ro->headers[ResponseHeader::WWW_AUTHENTICATE] = sprintf(
57 1
                'Bearer realm="token_required",error="token_not_found",error_description="%s"',
58 1
                $e->getMessage()
59
            );
60
61 1
            return $ro;
62
        }
63
64
        if ($e instanceof InvalidToken) {
65
            $ro->code = StatusCode::UNAUTHORIZED;
66
            $ro->headers[ResponseHeader::WWW_AUTHENTICATE] = sprintf(
67
                'Bearer realm="token_required",error="invalid_token",error_description="%s"',
68
                $e->getMessage()
69
            );
70
71
            return $ro;
72
        }
73
74
        throw $e;
75
    }
76
}
77