HashAuthenticator::getExpectedHash()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
ccs 1
cts 1
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 1
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