Completed
Push — master ( 000445...c8f0e6 )
by
unknown
04:21
created

SignatureParameterHandler::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 0
cts 5
cp 0
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 2
crap 2
1
<?php
2
3
namespace MediaMonks\SonataMediaBundle\Handler;
4
5
use MediaMonks\SonataMediaBundle\Model\MediaInterface;
6
use Symfony\Component\HttpFoundation\Request;
7
8
class SignatureParameterHandler implements ParameterHandlerInterface
9
{
10
    const PARAMETER_SIGNATURE = 's';
11
12
    /**
13
     * @var string
14
     */
15
    private $key;
16
17
    /**
18
     * @var string
19
     */
20
    private $hashAlgorithm;
21
22
    /**
23
     * @param $key
24
     * @param string $hashAlgorithm
25
     */
26
    public function __construct($key, $hashAlgorithm = 'sha256')
27
    {
28
        $this->key = $key;
29
        $this->hashAlgorithm = $hashAlgorithm;
30
    }
31
32
    /**
33
     * @param MediaInterface $media
34
     * @param array $parameters
35
     * @return string
36
     */
37
    public function getQueryString(MediaInterface $media, array $parameters)
38
    {
39
        $parameters = $this->normalize($parameters);
40
        $parameters[self::PARAMETER_SIGNATURE] = $this->calculateSignature($parameters);
41
42
        return http_build_query($parameters);
43
    }
44
45
    /**
46
     * @param MediaInterface $media
47
     * @param Request $request
48
     * @return array
49
     * @throws \Exception
50
     */
51
    public function getPayload(MediaInterface $media, Request $request)
52
    {
53
        $parameters = $request->query->all();
54
        if (!$this->isValid($parameters + ['id' => $media->getId()])) {
55
            throw new \Exception('Invalid Signature');
56
        }
57
58
        return $parameters;
59
    }
60
61
62
    /**
63
     * @param array $parameters
64
     * @return bool
65
     */
66
    private function isValid(array $parameters)
67
    {
68
        return !hash_equals($this->calculateSignature($parameters), $parameters[self::PARAMETER_SIGNATURE]);
69
    }
70
71
    /**
72
     * @param array $parameters
73
     * @return string
74
     */
75
    private function calculateSignature(array $parameters)
76
    {
77
        return hash_hmac($this->hashAlgorithm, $this->key, json_encode($this->normalize($parameters)));
78
    }
79
80
    /**
81
     * @param array $parameters
82
     * @return array
83
     */
84
    private function normalize(array $parameters)
85
    {
86
        if (isset($parameters[self::PARAMETER_SIGNATURE])) {
87
            unset($parameters[self::PARAMETER_SIGNATURE]);
88
        }
89
        ksort($parameters);
90
91
        return $parameters;
92
    }
93
}
94