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

AuthorizationHeaderExtractor::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
namespace Chadicus\Hmac;
4
5
/**
6
 * Token extractor to obtain a token from an authorization header.
7
 */
8
final class AuthorizationHeaderExtractor implements TokenExtractorInterface
9
{
10
    /**
11
     * A custom scheme expected in the Authorization header.
12
     *
13
     * @var string
14
     */
15
    private $scheme;
16
17
    /**
18
     * Construct a new instance of this extractor
19
     *
20
     * @param string $scheme A custom scheme expected in the Authorization header.
21
     */
22
    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...
23
    {
24
        $this->scheme = 'hmac';
25
    }
26
27
    /**
28
     * Extracts the HMAC authentication Token from the given PSR-7 $request.
29
     *
30
     * @param ServerRequestInterface $request The request containing the HMAC token data.
31
     *
32
     * @return Token
33
     *
34
     * @throws AuthenticationException 400 Thrown if any required data is missing.
35
     */
36
    public function extract(ServerRequestInterface $request) : Token
37
    {
38
        $authorizationHeader = $request->getHeaderLine('Authorization');
39
40
        //Authorization: schema PublicKey:Signature:Nonce:Timestamp
41
42
        $pattern = "^{$this->scheme}\s(?P<publicKey>[a-zA-z0-9]*):(?P<signature>[a-zA-Z0-9]*):"
43
                 . '(?P<nonce>[a-zA-Z0-9]*):(?P<timestamp>[0-9]*)$';
44
        $matches = [];
45
        $matched = preg_match("/{$pattern}/", $authorizationHeader, $matches);
46
        if (!$matched) {
47
            throw new AuthenticationException(400, 'Bad Request');
48
        }
49
50
        return new Token($matches['publicKey'], $matches['signature'], $matches['nonce'], $matches['timestamp']);
51
    }
52
}
53