Completed
Push — master ( a96eef...84c2f0 )
by Marcel
30s
created

Verifier   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 57
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 6
c 1
b 0
f 0
lcom 1
cbo 3
dl 0
loc 57
ccs 22
cts 22
cp 1
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A verify() 0 16 2
A withoutUnsignedHeaders() 0 12 3
1
<?php
2
3
namespace UMA\Psr\Http\Message\HMAC;
4
5
use Psr\Http\Message\MessageInterface;
6
use UMA\Psr\Http\Message\Serializer\MessageSerializer;
7
8
class Verifier
9
{
10
    /**
11
     * @var Calculator
12
     */
13
    private $calculator;
14
15 72
    public function __construct()
16 1
    {
17 72
        $this->calculator = new Calculator();
18 72
    }
19
20
    /**
21
     * @param MessageInterface $message
22
     * @param string           $secret
23
     *
24
     * @return bool Signature verification outcome.
25
     *
26
     * @throws \InvalidArgumentException When $message is an implementation of
27
     *                                   MessageInterface that cannot be
28
     *                                   serialized and thus neither verified.
29
     */
30 72
    public function verify(MessageInterface $message, $secret)
31
    {
32 72
        if (0 === preg_match(
33 72
            '#^'.Specification::AUTH_PREFIX.' ([+/0-9A-Za-z]{43}=)$#',
34 72
            $message->getHeaderLine(Specification::AUTH_HEADER), $matches)
35 72
        ) {
36 2
            return false;
37
        }
38
39 70
        $clientSideSignature = $matches[1];
40
41 70
        $serverSideSignature = $this->calculator
42 70
            ->hmac(MessageSerializer::serialize($this->withoutUnsignedHeaders($message)), $secret);
43
44 70
        return hash_equals($serverSideSignature, $clientSideSignature);
45
    }
46
47
    /**
48
     * @param MessageInterface $message
49
     *
50
     * @return MessageInterface
51
     */
52 70
    private function withoutUnsignedHeaders(MessageInterface $message)
53
    {
54 70
        $signedHeaders = array_filter(explode(',', $message->getHeaderLine(Specification::SIGN_HEADER)));
55
56 70
        foreach ($message->getHeaders() as $name => $value) {
57 70
            if (!in_array(mb_strtolower($name), $signedHeaders)) {
58 70
                $message = $message->withoutHeader($name);
59 70
            }
60 70
        }
61
62 70
        return $message;
63
    }
64
}
65