alexanoid
alexanoid

Reputation: 25790

How to programmatically recreate php yii session?

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

Upvotes: 2

Views: 1000

Answers (2)

icefront
icefront

Reputation: 174

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

Upvotes: 1

Asgaroth
Asgaroth

Reputation: 4334

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.

Upvotes: 5

Related Questions