Completed
Push — master ( 854a6f...c7bd33 )
by Chad
12s
created

TokenValidator   A

Complexity

Total Complexity 2

Size/Duplication

Total Lines 27
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 3

Importance

Changes 0
Metric Value
wmc 2
lcom 0
cbo 3
dl 0
loc 27
rs 10
c 0
b 0
f 0
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