|
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
|
|
|
|