简体   繁体   中英

How to login a user after registration in yii

Im not sure how can I login a user right after hes creation using yii framework.

In UserController I created the actionRegister in order to allow a user to create a new acccount, here if the user is successfully saved to db I would like to preform the login for this user aswell. Heres my code:

    public function actionRegister()
    {
        $model=new User;

        if(isset($_POST['User']))
        {
            $model->attributes=$_POST['User'];

            if($model->save()){            

                $identity=new UserIdentity($model->email,$model->password);
                $identity->authenticate();
                Yii::app()->user->login($identity);

                $this->redirect(array('view','id'=>$model->id));                
            }
        }
        $this->render('register',array('model'=>$model));
    }

Thank you in advance for any help u can give me in this matter.

I solved this by adding some code to UserIdentity class:

class UserIdentity extends CUserIdentity
{
    private $_id;

    //...

    public function setUpUser($user_id)
    {
        $this->_id=$user_id;
    }
}

So, setting the id in the CUserIdentity instance, you do not need to authenticate it. Just do:

$identity=new UserIdentity($model->email,'');
$identity->setUpUser($id); // id of user
Yii::app()->user->login($identity);

That's all.

Ok, seems like I'm answering my own question...

Turns out that $this->redirect(array('view','id'=>$model->id)); was not letting the login happen for some obscure reason... I can't answer to that since I started learning yii yesterday, but would appreciate if anyone with the knowledge could justify it.

So the solution is just remove the redirect and we got a user logged in user right after the account creation.

Thank you for trying to help John and Jay =)

Instead of removing $this->redirect(...); or using second parameter

redirect (..., $terminate =true, ...)
$terminate - whether to terminate the current application after calling this method. Defaults to true.

You can also put $this->redirect(...); under if statement, like this:

if($model->save()) {
    $identity=new UserIdentity($email,$password);
    $identity->authenticate();
    if(Yii::app()->user->login($identity))
        $this->redirect(array('account/profile','id'=>$model->id));
}

But of course this isn't final solution, you might need to use else as well in your individual cases.

Also using $this->redirect(..., false); with second parameter works as well, thanks lucifurious .

$this->redirect(array('account/profile','id'=>$model->id), false);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM