AccessControl.php
2.72 KB
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
100
<?php
namespace backend\components\filters;
use Yii;
use yii\helpers\ArrayHelper;
use yii\web\ForbiddenHttpException;
/**
*
* @author wuxiao
* @date 2016-8-19
*/
class AccessControl extends \yii\filters\AccessControl
{
/**
* @var array a list of access rule objects or configuration arrays for creating the rule objects.
* If a rule is specified via a configuration array, it will be merged with [[ruleConfig]] first
* before it is used for creating the rule object.
* @see ruleConfig
*/
public $rules = [
[
'allow' => true,
'roles' => ['@'],
],
];
public function init()
{
$rules = [];
/**
* 验证用户访问权限
*/
$route = Yii::$app->controller->id.'/'.Yii::$app->controller->action->id;
if (!self::verifyAccess($route)){
$rules = [['allow'=>false]];
}
$this->rules = ArrayHelper::merge($rules, $this->rules);
$this->denyCallback = function ($rule, $action) {
if (Yii::$app->user->getIsGuest()) {
Yii::$app->user->loginRequired();
} else {
//throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
Yii::$app->response->content = Yii::$app->view->render('@app/views/site/403',['_refer'=>Yii::$app->request->referrer]);
Yii::$app->response->send();
Yii::$app->end(1);
}
};
parent::init();
}
/**
* 验证用户访问权限
* @param type $permission 权限标签
* @return boolean
*/
static function verifyAccess($permissionName)
{
/**
* 首先判断具有强制通过验证权限
*/
if (self::forceAccess() === true){
return true;
}
return Yii::$app->authManager->checkAccess(Yii::$app->user->getId(), $permissionName);
}
/**
* 判断是否具有强制通过验证权限
* @staticvar type $forceAccess
* @return boolean
*/
static function forceAccess()
{
static $forceAccess;
if ($forceAccess === null)
{
if (isset(Yii::$app->params['verifyAccess']) && !Yii::$app->params['verifyAccess'])
{
$forceAccess = true;
}elseif (in_array(Yii::$app->user->getId(),Yii::$app->authManager->getUserIdsByRole('admin'))){
$forceAccess = true;
}else{
$forceAccess = false;
}
}
return $forceAccess;
}
public function beforeAction($action)
{
return parent::beforeAction($action);
}
}