Completed
Push — master ( efa379...854a6f )
by Chad
11s
created

TokenValidator::validate()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 13
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 8
nc 2
nop 3
1
<?php
2
3
namespace Chadicus\Hmac;
4
5
use Psr\Http\Message\ServerRequestInterface;
6
7
/**
8
 * Interface for validating token data.
9
 */
10
final class TokenValidator implements TokenValidatorInterface
11
{
12
    /**
13
     * Validates the given token against the private key and incoming request.
14
     *
15
     * @param string                 $privateKey The private API key.
16
     * @param Token                  $token      The token extracted from the request.
17
     * @param ServerRequestInterface $request    The incoming PSR-7 request.
18
     *
19
     * @return boolean
20
     *
21
     * @throws AuthenticationException 401 Thrown hash is not valid.
22
     */
23
    public function validate(string $privateKey, Token $token, ServerRequestInterface $request) : bool
24
    {
25
        $method = $request->getMethod();
26
        $uri = (string)$request->getUri();
27
        $base64 = base64_encode((string)$request->getBody());
28
        $data = "{$privateKey}{$method}{$uri}{$token->getTimeStamp()}{$token->getNonce()}{$base64}";
29
30
        if (hash('sha256', $data) !== $token->getSignature()) {
31
            throw new AuthenticationException(401, 'Invalid Hash');
32
        }
33
34
        return true;
35
    }
36
}
37