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

ValidateAuthenticationFilter   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 6
c 0
b 0
f 0
lcom 1
cbo 3
dl 0
loc 51
ccs 0
cts 21
cp 0
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A beforeAction() 0 15 3
A validateAuthentication() 0 8 1
A denyAccess() 0 8 2
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