Completed
Push — master ( 854a6f...c7bd33 )
by Chad
12s
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\Psr\Http\ServerMiddleware\Hmac;
4
5
use Chadicus\Psr\Http\ServerMiddleware\Token;
6
use Chadicus\Psr\Http\ServerMiddleware\TokenValidatorInterface;
7
use Psr\Http\Message\ServerRequestInterface;
8
9
/**
10
 * Interface for validating token data.
11
 */
12
final class TokenValidator implements TokenValidatorInterface
13
{
14
    /**
15
     * Validates the given token against the private key and incoming request.
16
     *
17
     * @param string                 $privateKey The private API key.
18
     * @param Token                  $token      The token extracted from the request.
19
     * @param ServerRequestInterface $request    The incoming PSR-7 request.
20
     *
21
     * @return boolean
22
     *
23
     * @throws AuthenticationException 401 Thrown hash is not valid.
24
     */
25
    public function validate(string $privateKey, Token $token, ServerRequestInterface $request) : bool
26
    {
27
        $method = $request->getMethod();
28
        $uri = (string)$request->getUri();
29
        $base64 = base64_encode((string)$request->getBody());
30
        $data = "{$privateKey}{$method}{$uri}{$token->getTimeStamp()}{$token->getNonce()}{$base64}";
31
32
        if (hash('sha256', $data) !== $token->getSignature()) {
33
            throw new AuthenticationException(401, 'Invalid Hash');
34
        }
35
36
        return true;
37
    }
38
}
39