我还是 yii2 的新手,我正在尝试让我的管理员用户能够切换到另一个用户,以便他可以看到与该用户完全相同的页面(如果他们报告了任何问题/错误)。
我找到了 switchIdentity()
方法,但我就是不知道如何调用这个 $identity
.
顺便说一句,你们认为这是管理员检查“用户 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.
}
现在我们更改了用户,我们只需要检查 session 是否存储了管理员 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');
我希望这可以帮助某人,对不起,我不知道如何在评论中正确编辑代码。
关于login - Yii2如何更改当前用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30442609/