控制器里重写beforeAction,behaviors 失效 [ 2.0 版本 ]
控制器代码:
public function behaviors() {
return [
//附加行为
'myBehavior' => [
'class' => '\app\components\MyBehavior',
],
'access' => [
'class' => AccessControl::className(),
'only' => ['index', 'add'],
'rules' => [
[
'actions' => [],
'allow' => true,
'roles' => ['?'],
],
[
'actions' => ['index', 'add'],
'allow' => true,
'roles' => ['@'],
]
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
//'delete' => ['POST'],
],
],
];
}
public function beforeAction($action) {
$currentaction = $action->id;
$novalidactions = ['add-edit-inspection-area']; //对这个action 关闭csrf
if (in_array($currentaction, $novalidactions)) {
$action->controller->enableCsrfValidation = false;
}
parent::beforeAction($action);
return true;
}
MyBehavior代码:
public function beforeAction($action) {
// 当前路由
$actionId = $action->getUniqueId();
$actionId = '/' . $actionId;
// 当前登录用户的id
$user = Yii::$app->getUser();
$userId = $user->id;
// 获取当前用户已经分配过的路由权限
// 写的比较简单,有过基础的可自行完善,比如解决"*"的问题,看不懂的该行注释自行忽略
$routes = [];
$manager = Yii::$app->getAuthManager();
foreach ($manager->getPermissionsByUser($userId) as $name => $value) {
if ($name[0] === '/') {
$routes[] = $name;
}
}
//print_r($routes);//所有权限
if ($actionId != '/auth/index') {//登录页面可直接访问
// 判断当前用户是否有权限访问正在请求的路由
if (in_array($actionId, $routes)) {
$this->navData($routes, $actionId);
return true;
}
} else {
return true;
}
$this->denyAccess($user);
}
发现我不重写beforeAction()方法,就正常,否则行为就失效
共 2 个回答
xyf90314
注册时间:2015-03-04
最后登录:2023-03-13
在线时长:95小时23分
最后登录:2023-03-13
在线时长:95小时23分
- 粉丝21
- 金钱5257
- 威望40
- 积分6607