HashAuthenticator   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 6
eloc 11
dl 0
loc 47
ccs 12
cts 12
cp 1
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A getExpectedHash() 0 3 1
A __construct() 0 5 1
A getRequestedHash() 0 3 1
A authenticate() 0 12 3
1
<?php
2
3
namespace kalanis\Restful\Security\Authentication;
4
5
6
use kalanis\Restful\Http\IInput;
7
use kalanis\Restful\Security\Exceptions\AuthenticationException;
8
use kalanis\Restful\Security\IAuthTokenCalculator;
9
use Nette\Http\IRequest;
10
11
12
/**
13
 * Verify request hashing data and comparing the results
14
 * @package kalanis\Restful\Security\Authentication
15
 */
16 1
class HashAuthenticator implements IRequestAuthenticator
17
{
18
19
    /** Auth token request header name */
20
    public const AUTH_HEADER = 'X-HTTP-AUTH-TOKEN';
21
22 1
    public function __construct(
23
        protected IRequest                             $request,
24
        protected IAuthTokenCalculator                 $calculator,
25
    )
26
    {
27 1
    }
28
29
    /**
30
     * @throws AuthenticationException
31
     */
32
    public function authenticate(IInput $input): bool
33
    {
34 1
        $requested = $this->getRequestedHash();
35 1
        if (!$requested) {
36 1
            throw new AuthenticationException('Authentication header not found.');
37
        }
38
39 1
        $expected = $this->getExpectedHash($input);
40 1
        if ($requested !== $expected) {
41 1
            throw new AuthenticationException('Authentication tokens do not match.');
42
        }
43 1
        return true;
44
    }
45
46
47
    /**
48
     * Get request hash
49
     * @return string|null
50
     */
51
    protected function getRequestedHash(): ?string
52
    {
53 1
        return $this->request->getHeader(self::AUTH_HEADER);
54
    }
55
56
    /**
57
     * Get expected hash
58
     * @return string
59
     */
60
    protected function getExpectedHash(IInput $input): string
61
    {
62 1
        return $this->calculator->calculate($input);
63
    }
64
}
65