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

查看:173
本文介绍了如何在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天全站免登陆