ValidateAuthenticationFilter   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
dl 0
loc 52
c 0
b 0
f 0
wmc 7
lcom 1
cbo 2
ccs 0
cts 26
cp 0
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A validateAuthentication() 0 8 1
A denyAccess() 0 8 2
A beforeAction() 0 17 4
1
<?php
2
/**
3
 * Multi-factor authentication for Yii2 projects
4
 *
5
 * @link      https://github.com/hiqdev/yii2-mfa
6
 * @package   yii2-mfa
7
 * @license   BSD-3-Clause
8
 * @copyright Copyright (c) 2016-2018, HiQDev (http://hiqdev.com/)
9
 */
10
11
namespace hiqdev\yii2\mfa\filters;
12
13
use Closure;
14
use hiqdev\yii2\mfa\base\MfaIdentityInterface;
15
use hiqdev\yii2\mfa\exceptions\AuthenticationException;
16
use hiqdev\yii2\mfa\exceptions\NotAuthenticatedException;
17
use hiqdev\yii2\mfa\Module;
18
use Yii;
19
use yii\base\ActionFilter;
20
use yii\web\IdentityInterface;
21
22
class ValidateAuthenticationFilter extends ActionFilter
23
{
24
    /**
25
     * @var Closure
26
     */
27
    public $denyCallback;
28
29
    /**
30
     * @var bool
31
     */
32
    public $invert = false;
33
34
    public function beforeAction($action)
35
    {
36
        /** @var MfaIdentityInterface $identity */
37
        $identity = Yii::$app->user->identity;
38
39
        if (Yii::$app->user->isGuest || $identity === null) {
40
            return true;
41
        }
42
43
        try {
44
            $this->validateAuthentication($identity);
45
        } catch (AuthenticationException $e) {
46
            return $this->denyAccess($e);
47
        }
48
49
        return true;
50
    }
51
52
    public function validateAuthentication(MfaIdentityInterface $identity)
53
    {
54
        /** @var Module $module */
55
        $module = Yii::$app->getModule('mfa');
56
57
        $module->validateIps($identity);
58
        $module->validateTotp($identity);
59
    }
60
61
    /**
62
     * @param AuthenticationException $exception
63
     * @return mixed
64
     */
65
    protected function denyAccess($exception)
66
    {
67
        if ($this->denyCallback instanceof Closure) {
68
            return call_user_func($this->denyCallback, $exception);
69
        }
70
71
        $exception->redirect();
72
    }
73
}
74