我有登录的控制器代码:
public function actionLogin()
{
if (!\Yii::$app->user->isGuest) {
return $this->redirect(Yii::$app->request->baseUrl.'/telephone/index');
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login()) {
return $this->redirect(Yii::$app->request->baseUrl.'/telephone/index');
}
return $this->render('login', [
'model' => $model,
]);
}
为防止我使用的未授权用户add
和delete
操作:
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['add','delete'],
'rules' => [
// allow authenticated users
[
'allow' => true,
'roles' => ['@'],
],
// everything else is denied by default
],
],
];
}
但是,如果未经授权的用户clik添加或删除,则会将其重定向到site/login
。如何更改控制器和操作?
答案 0 :(得分:3)
根据范围,有不同的方法来更改该路线。它们都涉及更改loginUrl
类的yii\web\User
属性。
<强>全球强>
编辑配置文件。
'components' => [
'user' => [
'loginUrl' => ["controller/action"],
],
],
<强>控制器/动作强>
编辑控制器的beforeAction方法。
public function beforeAction($action)
{
// action-specific
if(in_array($action->id,['not', 'allowed', 'actions']))
Yii::$app->user->loginUrl = ["controller/action"];
// controller-wide
Yii::$app->user->loginUrl = ["controller/action"];
if (!parent::beforeAction($action)) {
return false;
}
return true;
}
答案 1 :(得分:-1)
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['add','delete'],
'rules' => [
'allow' => true,
'actions' => ['add','delete'],
'roles' => ['@'],
'denyCallback' => function ($rule, $action) {
return $this->redirect('index.php?r=site/login');
}
],
],
];
}