|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace kalanis\Restful\Security; |
|
4
|
|
|
|
|
5
|
|
|
|
|
6
|
|
|
use kalanis\Restful\Exceptions\InvalidStateException; |
|
7
|
|
|
use kalanis\Restful\Http\IInput; |
|
8
|
|
|
use kalanis\Restful\Mapping\IMapper; |
|
9
|
|
|
use kalanis\Restful\Mapping\MapperContext; |
|
10
|
|
|
use Nette\Http\IRequest; |
|
11
|
|
|
|
|
12
|
|
|
|
|
13
|
|
|
/** |
|
14
|
|
|
* Default auth token calculator implementation |
|
15
|
|
|
* @package kalanis\Restful\Security |
|
16
|
|
|
*/ |
|
17
|
1 |
|
class HashCalculator implements IAuthTokenCalculator |
|
18
|
|
|
{ |
|
19
|
|
|
|
|
20
|
|
|
/** Fingerprint hash algorithm */ |
|
21
|
|
|
public const HASH = 'sha256'; |
|
22
|
|
|
|
|
23
|
|
|
private string $privateKey = ''; |
|
24
|
|
|
|
|
25
|
|
|
private IMapper $mapper; |
|
26
|
|
|
|
|
27
|
|
|
public function __construct( |
|
28
|
|
|
MapperContext $mapperContext, |
|
29
|
|
|
IRequest $httpRequest, |
|
30
|
|
|
) |
|
31
|
|
|
{ |
|
32
|
1 |
|
$this->mapper = $mapperContext->getMapper($httpRequest->getHeader('content-type')); |
|
33
|
1 |
|
} |
|
34
|
|
|
|
|
35
|
|
|
/** |
|
36
|
|
|
* Set hash data calculator mapper |
|
37
|
|
|
*/ |
|
38
|
|
|
public function setMapper(IMapper $mapper): static |
|
39
|
|
|
{ |
|
40
|
|
|
$this->mapper = $mapper; |
|
41
|
|
|
return $this; |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
/** |
|
45
|
|
|
* Set hash calculator security private key |
|
46
|
|
|
* @param string $key |
|
47
|
|
|
* @return $this |
|
48
|
|
|
*/ |
|
49
|
|
|
public function setPrivateKey(#[\SensitiveParameter] string $key): static |
|
50
|
|
|
{ |
|
51
|
1 |
|
$this->privateKey = $key; |
|
52
|
1 |
|
return $this; |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
/** |
|
56
|
|
|
* Calculates hash |
|
57
|
|
|
* |
|
58
|
|
|
* @throws InvalidStateException |
|
59
|
|
|
*/ |
|
60
|
|
|
public function calculate(IInput $input): string |
|
61
|
|
|
{ |
|
62
|
1 |
|
if (empty($this->privateKey)) { |
|
63
|
|
|
throw new InvalidStateException('Private key is not set'); |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
1 |
|
$dataString = $this->mapper->stringify($input->getData(), false); |
|
67
|
1 |
|
return hash_hmac(self::HASH, $dataString, $this->privateKey); |
|
68
|
|
|
} |
|
69
|
|
|
} |
|
70
|
|
|
|