|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Covery\Client\Credentials; |
|
4
|
|
|
|
|
5
|
|
|
use Covery\Client\CredentialsInterface; |
|
6
|
|
|
use Psr\Http\Message\RequestInterface; |
|
7
|
|
|
|
|
8
|
|
|
class Sha256 implements CredentialsInterface |
|
9
|
|
|
{ |
|
10
|
|
|
/** |
|
11
|
|
|
* @var string |
|
12
|
|
|
*/ |
|
13
|
|
|
private $token; |
|
14
|
|
|
/** |
|
15
|
|
|
* @var string |
|
16
|
|
|
*/ |
|
17
|
|
|
private $secret; |
|
18
|
|
|
|
|
19
|
|
|
/** |
|
20
|
|
|
* Sha256 credentials constructor |
|
21
|
|
|
* |
|
22
|
|
|
* @param string $token |
|
23
|
|
|
* @param string $secret |
|
24
|
|
|
* @throws \Exception |
|
25
|
|
|
*/ |
|
26
|
|
|
public function __construct($token, $secret) |
|
27
|
|
|
{ |
|
28
|
|
|
if (!is_string($token)) { |
|
29
|
|
|
throw new \InvalidArgumentException('Token must be string'); |
|
30
|
|
|
} elseif (strlen($token) !== 32) { |
|
31
|
|
|
throw new \InvalidArgumentException('Token must be exact 32 characters long'); |
|
32
|
|
|
} |
|
33
|
|
|
if (!is_string($secret)) { |
|
34
|
|
|
throw new \InvalidArgumentException('Secret must be string'); |
|
35
|
|
|
} elseif (strlen($secret) !== 32) { |
|
36
|
|
|
throw new \InvalidArgumentException('Secret must be exact 32 characters long'); |
|
37
|
|
|
} |
|
38
|
|
|
if (!function_exists('hash')) { |
|
39
|
|
|
throw new \Exception('Unable to build Sha256 credentials - function "hash" not exists'); |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
$this->token = $token; |
|
43
|
|
|
$this->secret = $secret; |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
|
|
/** |
|
47
|
|
|
* Signs provided HTTP request |
|
48
|
|
|
* |
|
49
|
|
|
* @param RequestInterface $request |
|
50
|
|
|
* @return RequestInterface |
|
51
|
|
|
*/ |
|
52
|
|
|
public function signRequest(RequestInterface $request) |
|
53
|
|
|
{ |
|
54
|
|
|
// Generating random NONCE |
|
55
|
|
|
$nonce = microtime(true) . mt_rand(); |
|
56
|
|
|
|
|
57
|
|
|
// Generating signature |
|
58
|
|
|
$stream = $request->getBody(); |
|
59
|
|
|
$body = $stream->getContents(); |
|
60
|
|
|
$signature = hash('sha256', $nonce . $body . $this->secret); |
|
61
|
|
|
|
|
62
|
|
|
// Rewinding/rebuilding |
|
63
|
|
|
if ($stream->isSeekable()) { |
|
64
|
|
|
$stream->rewind(); |
|
65
|
|
|
} else { |
|
66
|
|
|
$stream->close(); |
|
67
|
|
|
$stream = \GuzzleHttp\Psr7\stream_for($body); |
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
|
|
return $request |
|
71
|
|
|
->withBody($stream) |
|
72
|
|
|
->withHeader('X-Auth-Token', $this->token) |
|
73
|
|
|
->withHeader('X-Auth-Nonce', $nonce) |
|
74
|
|
|
->withHeader('X-Auth-Signature', $signature) |
|
75
|
|
|
->withHeader('X-Auth-Version', '1.0'); |
|
76
|
|
|
} |
|
77
|
|
|
} |
|
78
|
|
|
|