2

From my application view I need to programmatically logout current user and login another one right after that.

I want to login the second user into his own different CHttpSession (with another sessionID and so on). I need it for a security reasons.

How to implement this in Yii framework ?

Code below

$oSession->destroy(); $oSession->open();

doesn't work as expected..

1
  • Re-create session have to be before any output to client. if you create session, output some data - recreate session will not work. You have to create session, delete session, and recreate session after this output some data. Or you have to use buffer output Commented Oct 16, 2012 at 4:35

2 Answers 2

5

looks like you are trying to impersonate users:

  1. Create a function in your UserIdentity that would alow you to login as another known user:

    protected function logInUser($user)
    {
        if($user)
        {
            $this->_user = $user;
            $this->_id=$this->_user->id;
            $this->setState('name', $this->_user->name);
            $this->errorCode=self::ERROR_NONE;
        }
    }
    
  2. In your controller, call this function to get the UserIdentity object and then use the Yii's CWebUser login

    $ui = null;
    $user = User::model()->findByPk($userId);
    if($user)
    {   
        $ui = new UserIdentity($user->email, "");
        $ui->logInUser($user);
    }
    Yii::app()->user->login($ui, 0);
    

Remember to protect this controller's action from non authorized users.

Sign up to request clarification or add additional context in comments.

Comments

1

A possible tricky way (tested):

session_unset();
Yii::app()->user->id = $the_new_id;

When the above code is executed, nothing visible happens on the page so you may want to redirect the browser:

$this->redirect('somewhere');

Upon the next page load, the user with the $the_new_id will be logged in

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.