AuthorizationHeaderExtractor   A
last analyzed

Complexity

Total Complexity 3

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
wmc 3
lcom 1
cbo 3
dl 0
loc 45
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A extract() 0 16 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\TokenExtractorInterface;
8
use Psr\Http\Message\ServerRequestInterface;
9
10
/**
11
 * Token extractor to obtain a token from an authorization header.
12
 */
13
final class AuthorizationHeaderExtractor implements TokenExtractorInterface
14
{
15
    /**
16
     * A custom scheme expected in the Authorization header.
17
     *
18
     * @var string
19
     */
20
    private $scheme;
21
22
    /**
23
     * Construct a new instance of this extractor
24
     *
25
     * @param string $scheme A custom scheme expected in the Authorization header.
26
     */
27
    public function __construct(string $scheme = 'hmac')
0 ignored issues
show
Unused Code introduced by
The parameter $scheme is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
28
    {
29
        $this->scheme = 'hmac';
30
    }
31
32
    /**
33
     * Extracts the HMAC authentication Token from the given PSR-7 $request.
34
     *
35
     * @param ServerRequestInterface $request The request containing the HMAC token data.
36
     *
37
     * @return Token
38
     *
39
     * @throws AuthenticationException 400 Thrown if any required data is missing.
40
     */
41
    public function extract(ServerRequestInterface $request) : Token
42
    {
43
        $authorizationHeader = $request->getHeaderLine('Authorization');
44
45
        //Authorization: schema PublicKey:Signature:Nonce:Timestamp
46
47
        $pattern = "^{$this->scheme}\s(?P<publicKey>[a-zA-z0-9]*):(?P<signature>[a-zA-Z0-9]*):"
48
                 . '(?P<nonce>[a-zA-Z0-9]*):(?P<timestamp>[0-9]*)$';
49
        $matches = [];
50
        $matched = preg_match("/{$pattern}/", $authorizationHeader, $matches);
51
        if (!$matched) {
52
            throw new AuthenticationException(400, 'Bad Request');
53
        }
54
55
        return new Token($matches['publicKey'], $matches['signature'], $matches['nonce'], $matches['timestamp']);
56
    }
57
}
58