How to change current user in Yii2

2019-03-22 07:44发布

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).

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?

标签: login yii2
1条回答
爷、活的狠高调
2楼-- · 2019-03-22 08:24

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.
}

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.

查看更多
登录 后发表回答