TimeoutAuthenticator   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 33
Duplicated Lines 0 %

Test Coverage

Coverage 90.91%

Importance

Changes 0
Metric Value
wmc 5
eloc 9
dl 0
loc 33
ccs 10
cts 11
cp 0.9091
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A authenticate() 0 14 4
1
<?php
2
3
namespace kalanis\Restful\Security\Authentication;
4
5
6
use kalanis\Restful\Http\IInput;
7
use kalanis\Restful\Security\Exceptions\RequestTimeoutException;
8
9
10
/**
11
 * Verify request timeout to avoid replay attack (needs to be applied with any HashAuthenticator)
12
 * @package kalanis\Restful\Security\Authentication
13
 */
14 1
class TimeoutAuthenticator implements IRequestAuthenticator
15
{
16
17
    /**
18
     * @param string $requestTimeKey in user request data
19
     * @param int $timeout in milliseconds
20
     */
21 1
    public function __construct(
22
        #[\SensitiveParameter] private readonly string $requestTimeKey,
23
        private readonly int                           $timeout,
24
    )
25
    {
26 1
    }
27
28
    /**
29
     * Authenticate request timeout
30
     *
31
     * @throws RequestTimeoutException
32
     */
33
    public function authenticate(IInput $input): bool
34
    {
35 1
        $timestamp = time();
36 1
        $data = $input->getData();
37 1
        if (!isset($data[$this->requestTimeKey]) || !$data[$this->requestTimeKey]) {
38
            throw new RequestTimeoutException('Request time not found in requested data.');
39
        }
40
41 1
        $diff = $timestamp - $data[$this->requestTimeKey];
42 1
        if ($diff > $this->timeout) {
43 1
            throw new RequestTimeoutException('Request timeout');
44
        }
45
46 1
        return true;
47
    }
48
}
49