-
Notifications
You must be signed in to change notification settings - Fork 0
/
AccessControl.php
83 lines (74 loc) · 1.9 KB
/
AccessControl.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
<?php
namespace yiier\rbac\components;
use yii\web\ForbiddenHttpException;
use Yii;
use yii\base\Module;
use yii\web\User;
use yii\di\Instance;
class AccessControl extends \yii\base\ActionFilter
{
/**
* @var User User for check access.
*/
private $_user = 'user';
/**
* Get user
* @return User
*/
public function getUser()
{
if (!$this->_user instanceof User) {
$this->_user = Instance::ensure($this->_user, User::className());
}
return $this->_user;
}
/**
* Set user
* @param User|string $user
*/
public function setUser($user)
{
$this->_user = $user;
}
/**
* @inheritdoc
*/
public function beforeAction($action)
{
$user = $this->getUser();
$controllerId = $action->controller->id;
$moduleId = $action->controller->module->uniqueId ? '@' . $action->controller->module->uniqueId : '';
$app = explode('\\', get_class(Yii::$app->controller));
$permissionName = "{$app[0]}{$moduleId}_{$controllerId}_{$action->id}";
if (Yii::$app->authManager->getPermission($permissionName)) {
if (Yii::$app->user->can($permissionName)) {
return true;
}
$this->denyAccess($user);
}
return true;
}
/**
* @param $user
* @throws ForbiddenHttpException
*/
protected function denyAccess($user)
{
if ($user->getIsGuest()) {
$user->loginRequired();
} else {
throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
}
}
/**
* @inheritdoc
*/
protected function isActive($action)
{
$uniqueId = $action->getUniqueId();
if ($uniqueId === Yii::$app->getErrorHandler()->errorAction) {
return false;
}
return true;
}
}