Completed
Push — master ( 89ee1f...c82ddc )
by Dmitry
02:01
created

ValidateAuthenticationFilter::denyAccess()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 8
ccs 0
cts 3
cp 0
rs 9.4285
cc 2
eloc 4
nc 2
nop 1
crap 6
1
<?php
2
3
namespace hiqdev\yii2\mfa\filters;
4
5
use Closure;
6
use hiqdev\yii2\mfa\exceptions\AuthenticationException;
7
use hiqdev\yii2\mfa\exceptions\NotAuthenticatedException;
8
use hiqdev\yii2\mfa\Module;
9
use Yii;
10
use yii\base\ActionFilter;
11
use yii\web\IdentityInterface;
12
13
class ValidateAuthenticationFilter extends ActionFilter
14
{
15
    /**
16
     * @var Closure
17
     */
18
    public $denyCallback;
19
20
    /**
21
     * @var bool
22
     */
23
    public $invert = false;
24
25
    public function beforeAction($action)
26
    {
27
        if (Yii::$app->user->isGuest) {
28
            return $this->denyAccess(new NotAuthenticatedException());
29
        }
30
31
        $identity = Yii::$app->user->identity;
32
        try {
33
            $this->validateAuthentication($identity);
34
        } catch (AuthenticationException $e) {
35
            return $this->denyAccess($e);
36
        }
37
38
        return true;
39
    }
40
41
    public function validateAuthentication(IdentityInterface $identity)
42
    {
43
        /** @var Module $module */
44
        $module = Yii::$app->getModule('mfa');
45
46
        $module->validateIps($identity);
47
        $module->validateTotp($identity);
48
    }
49
50
    /**
51
     * @param AuthenticationException $exception
52
     * @return mixed
53
     */
54
    protected function denyAccess($exception)
55
    {
56
        if ($this->denyCallback instanceof Closure) {
57
            return call_user_func($this->denyCallback, $exception);
58
        }
59
60
        $exception->redirect();
61
    }
62
63
}
64