AuthInBearer::parse()   A
last analyzed

Complexity

Conditions 6
Paths 5

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 8
c 1
b 0
f 0
nc 5
nop 0
dl 0
loc 13
ccs 9
cts 9
cp 1
crap 6
rs 9.2222
1
<?php
2
3
declare(strict_types=1);
4
5
namespace LibraryCatalog\Service;
6
7
use Psr\Http\Message\RequestInterface;
8
9
class AuthInBearer implements AuthInInterface
10
{
11
    /** @var RequestInterface */
12
    protected RequestInterface $request;
13
    /** @var bool */
14
    protected bool $parsed = false;
15
    /** @var string */
16
    protected string $payload;
17
    /** @var bool */
18
    protected bool $isAuthenticated = false;
19
    /** @var string */
20
    protected string $secret;
21
22
    /**
23
     * AuthInBearer constructor.
24
     * @param string $secret
25
     */
26 1
    public function __construct(string $secret)
27
    {
28 1
        $this->secret = $secret;
29 1
    }
30
31
    /**
32
     * @param RequestInterface $request
33
     * @return AuthInInterface
34
     */
35 15
    public function setRequest(RequestInterface $request): AuthInInterface
36
    {
37 15
        $this->request = $request;
38 15
        $this->parsed = false;
39 15
        return $this;
40
    }
41
42
    /**
43
     * @return bool
44
     */
45 15
    public function authenticated(): bool
46
    {
47 15
        $this->parse();
48 15
        return $this->isAuthenticated;
49
    }
50
51
    /**
52
     * @return string
53
     */
54 13
    public function getPayload(): string
55
    {
56 13
        $this->parse();
57 13
        return $this->payload ?? '';
58
    }
59
60
    /**
61
     * @return void
62
     */
63 15
    protected function parse(): void
64
    {
65 15
        if (!$this->parsed) {
66 15
            if (isset($this->request)) {
67 15
                $bearer = $this->request->getHeader('Authorization');
68 15
                if (count($bearer) >= 1) {
69 14
                    $ar = explode(' ', $bearer[0]);
70 14
                    if (count($ar) >= 2 && $ar[0] === 'Bearer') {
71 14
                        $this->proceedData((string)base64_decode($ar[1]));
72
                    }
73
                }
74
            }
75 15
            $this->parsed = true;
76
        }
77 15
    }
78
79
    /**
80
     * @param string $data
81
     * @return void
82
     */
83 14
    protected function proceedData(string $data): void
84
    {
85 14
        $decoded = @json_decode($data);
86 14
        if ($decoded) {
87 14
            if (isset($decoded->secret) && $decoded->secret === $this->secret) {
88
                // Authenticate only if secret is valid.
89 14
                $this->isAuthenticated = true;
90 14
                if (isset($decoded->payload)) {
91 14
                    $this->payload = (string)$decoded->payload;
92
                }
93
            }
94
        }
95 14
    }
96
}
97