Yii2 修改当前用户
How to change current user in Yii2
我还是 yii2 的新手,我正在尝试让我的管理员用户能够切换到另一个用户,以便他可以看到与该用户完全一样的页面(如果他们报告任何 problem/bug)。
我找到了 switchIdentity()
方法,但我不知道如何调用它 $identity
。
顺便说一下,你们认为这是管理员检查 "user view" 或任何人有更好主意的最佳方式?
好的,我找到了解决办法。我们只需要我们想要登录的用户的 ID。我打电话给 $id
.
$initialId = Yii::$app->user->getId(); //here is the current ID, so you can go back after that.
if ($id == $initialId) {
//Same user!
} else {
$user = User::findOne($id);
$duration = 0;
Yii::$app->user->switchIdentity($user, $duration); //Change the current user.
Yii::$app->session->set('user.idbeforeswitch',$initialId); //Save in the session the id of your admin user.
return $this->render('index'); //redirect to any page you like.
}
既然我们改变了用户,我们只需要检查会话是否存储了管理员ID。如果是,可以调用一些操作返回到我们的原始用户。像这样:
$originalId = Yii::$app->session->get('user.idbeforeswitch');
if ($originalId) {
$user = User::findOne($originalId);
$duration = 0;
Yii::$app->user->switchIdentity($user, $duration);
Yii::$app->session->remove('user.idbeforeswitch');
}
return $this->render('index');
我希望这可以帮助别人,抱歉我不知道如何在评论中正确编辑代码。
我还是 yii2 的新手,我正在尝试让我的管理员用户能够切换到另一个用户,以便他可以看到与该用户完全一样的页面(如果他们报告任何 problem/bug)。
我找到了 switchIdentity()
方法,但我不知道如何调用它 $identity
。
顺便说一下,你们认为这是管理员检查 "user view" 或任何人有更好主意的最佳方式?
好的,我找到了解决办法。我们只需要我们想要登录的用户的 ID。我打电话给 $id
.
$initialId = Yii::$app->user->getId(); //here is the current ID, so you can go back after that.
if ($id == $initialId) {
//Same user!
} else {
$user = User::findOne($id);
$duration = 0;
Yii::$app->user->switchIdentity($user, $duration); //Change the current user.
Yii::$app->session->set('user.idbeforeswitch',$initialId); //Save in the session the id of your admin user.
return $this->render('index'); //redirect to any page you like.
}
既然我们改变了用户,我们只需要检查会话是否存储了管理员ID。如果是,可以调用一些操作返回到我们的原始用户。像这样:
$originalId = Yii::$app->session->get('user.idbeforeswitch');
if ($originalId) {
$user = User::findOne($originalId);
$duration = 0;
Yii::$app->user->switchIdentity($user, $duration);
Yii::$app->session->remove('user.idbeforeswitch');
}
return $this->render('index');
我希望这可以帮助别人,抱歉我不知道如何在评论中正确编辑代码。