Yii2如何更改当前用户 [英] How to change current user in Yii2

查看:16
本文介绍了Yii2如何更改当前用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我还是 yii2 的新手,我正在尝试让我的管理员用户能够切换到另一个用户,以便他可以看到与该用户完全相同的页面(如果他们报告了任何问题/错误).

I'm still new in yii2 and I'm trying to make my admin user able to switch to another user so he can see the pages exactly like this users (If they report any problem/bug).

我找到了 switchIdentity() 方法,但我就是不知道如何调用这个 $identity .

I found the switchIdentity() method, but I just can't figure out how to call this $identity .

顺便说一句,你们认为这是管理员检查用户视图"或任何人有更好的主意的最佳方式?

By the way, you guys think this is the best way for an admin check the "user view" or anyone have a better idea?

推荐答案

好的,我找到了解决方案.我们只需要我们想要登录的用户的 ID.我打电话给 $id.

OK, i found a solution. We just need the id of the user we want to login as. I called $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.如果是,则可以调用某些操作以返回到我们的原始用户.像这样:

Now that we changed the user, we just need to check if the session have stored the admin Id. If does, some action can be called to go back to our original user. Like this:

$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');

我希望这可以帮助某人,抱歉我不知道如何在评论中正确编辑代码.

I hope this can help someone and sorry i don't know how to edit the codes properly in the comments.

这篇关于Yii2如何更改当前用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆