Completed
Push — master ( 32af36...de0c2e )
by Sam
04:31
created

HmacFilter::init()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 7
ccs 4
cts 4
cp 1
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 0
crap 2
1
<?php
2
declare(strict_types=1);
3
4
5
namespace SamIT\Yii2\UrlSigner;
6
7
8
use SamIT\Yii2\UrlSigner\UrlSigner;
9
use yii\base\ActionFilter;
10
use yii\base\InvalidConfigException;
11
use yii\web\ForbiddenHttpException;
12
use yii\web\Request;
13
14
/**
15
 * Filter that checks for a valid HMAC in the URL.
16
 * @inheritdoc
17
 */
18
class HmacFilter extends ActionFilter
19
{
20
    /**
21
     * @var UrlSigner
22
     */
23
    public $signer;
24
25 10
    public function init()
26
    {
27 10
        parent::init();
28 10
        if (!$this->signer instanceof UrlSigner) {
29 4
            throw new InvalidConfigException('Signer is required');
30
        }
31
    }
32
33
34
    /**
35
     * @param \yii\base\Action $action
36
     * @throws \Exception
37
     * @return bool
38
     */
39 4
    public function beforeAction($action)
40
    {
41
        /**
42
         * We obtain the request this way because we do not want to store a reference to any objects with state.
43
         * @var Request $request
44
         */
45 4
        $request = $action->controller->module->get('request');
46 4
        if (!$this->signer->verify($request->queryParams, $action->controller->route)) {
47 2
            throw new ForbiddenHttpException("No or invalid HMAC");
48
        }
49 2
        return true;
50
    }
51
52
}
53