-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathComponent.php
99 lines (86 loc) · 2.52 KB
/
Component.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
<?php
namespace lajax\httpauth;
use Yii;
use yii\web\UnauthorizedHttpException;
/**
* Yii2 Http Authentication component.
*
* config:
*
* ~~~
* 'bootstrap' => ['httpAuth'],
* 'components' => [
* // ...
* 'httpAuth' => [
* 'class' => 'lajax\httpauth\Component',
* 'allowedIps' => ['127.0.0.1', '127.0.0.2'],
* 'users' => [
* 'mrsith' => '123456',
* 'mrssith' => 'e10adc3949ba59abbe56e057f20f883e',
* ],
* 'errorAction' => 'site/error',
* ],
* // ...
* ],
* // ...
* ~~~
*
* @author Lajos Molnár <lajax.m@gmail.com>
*
* @since 1.0
*/
class Component extends \yii\base\Component
{
/**
* @var string[] Username and password pairs. The value can be either an actual password,
* or an MD5 hash of the password.
*/
public $users;
/**
* @var string[] The list of IPs that are allowed to access this application.
*/
public $allowedIps = ['127.0.0.1', '::1'];
/**
* @var string The route of errorHandler page.
*/
public $errorAction;
/**
* @inheritdoc
*/
public function init()
{
if (Yii::$app->request->isConsoleRequest || $this->_checkAllowedIps() || $this->_checkHttpAuthentication()) {
return;
}
Yii::$app->response->headers->add('WWW-Authenticate', 'Basic realm="HTTP authentication"');
if ($this->errorAction) {
Yii::$app->errorHandler->errorAction = $this->errorAction;
}
throw new UnauthorizedHttpException(Yii::t('yii', 'You are not allowed to perform this action.'), 401);
}
/**
* @return bool Whether the application can be accessed by the current user.
*/
private function _checkAllowedIps()
{
$ip = Yii::$app->request->getUserIP();
foreach ($this->allowedIps as $filter) {
if ($filter === '*' || $filter === $ip || (($pos = strpos($filter, '*')) !== false && !strncmp($ip, $filter, $pos))) {
return true;
}
}
return false;
}
/**
* @return bool Whether the application can be accessed by the current user.
*/
private function _checkHttpAuthentication()
{
$username = Yii::$app->request->getAuthUser();
$password = Yii::$app->request->getAuthPassword();
if (isset($this->users[$username]) && ($password == $this->users[$username] || md5($password) == $this->users[$username])) {
return true;
}
return false;
}
}