TokenValidator   A
last analyzed

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 Method

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