BasicAuthAuthenticator::isAuth()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
cc 3
eloc 8
nc 3
nop 1
dl 0
loc 13
ccs 0
cts 11
cp 0
crap 12
rs 10
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
4
5
namespace Xervice\Service\Middleware\Security\Authenticator;
6
7
8
use Illuminate\Http\Request;
9
use Xervice\Service\Middleware\Security\Exception\AuthenticationFailed;
10
use Xervice\Service\Middleware\Security\Validator\ValidatorCollection;
11
12
class BasicAuthAuthenticator implements AuthenticatorInterface
13
{
14
    const HEADER = 'authorization';
15
16
    /**
17
     * @var \Xervice\Service\Middleware\Security\Validator\ValidatorCollection
18
     */
19
    private $validatorCollection;
20
21
    /**
22
     * BasicAuthAuthenticator constructor.
23
     *
24
     * @param \Xervice\Service\Middleware\Security\Validator\ValidatorCollection $validatorCollection
25
     */
26
    public function __construct(ValidatorCollection $validatorCollection)
27
    {
28
        $this->validatorCollection = $validatorCollection;
29
    }
30
31
    /**
32
     * @param \Illuminate\Http\Request $request
33
     *
34
     * @return bool
35
     */
36
    public function isAuth(Request $request): bool
37
    {
38
        $basicAuth = $request->header(self::HEADER, '');
39
        $token = $this->getToken($basicAuth);
40
41
        try {
42
            foreach ($this->validatorCollection as $validator) {
43
                $validator->validate($token);
44
            }
45
46
            return true;
47
        } catch (AuthenticationFailed $e) {
48
            return false;
49
        }
50
    }
51
52
53
    /**
54
     * @param string $basicAuth
55
     *
56
     * @return string
57
     */
58
    private function getToken(string $basicAuth) : string
59
    {
60
        return base64_decode(str_replace('Basic ', '', $basicAuth));
61
    }
62
63
}