How to log in after registration in yii

I'm not sure how I can log in for users right after creating hes using the yii framework.

In UserController, I created an actionRegister to allow the user to create a new acccount, here, if the user is successfully saved in db, I would also like to register for this user. Here is 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 you can give me in this matter.

+4
source share
3 answers

Well, it seems I am answering my question ...

It turns out that $this->redirect(array('view','id'=>$model->id)); it didn’t allow me to enter the system for some unclear reason ... I cannot answer this since I started to study yii yesterday, but I would be grateful if any of this knowledge could justify it.

Thus, the solution simply removes the redirect, and we got the user registered as a user immediately after creating the account.

Thanks for trying to help John and Jay =)

+3
source

I solved this by adding some code to the UserIdentity class:

 class UserIdentity extends CUserIdentity { private $_id; //... public function setUpUser($user_id) { $this->_id=$user_id; } } 

So, by setting the identifier 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); 

What all.

+3
source

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

redirection (..., $ terminate = true, ...)
$ terminate - Whether to terminate the current application after calling this method. The default value is true.

You can also put $this->redirect(...); into an if statement, for example:

 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 is not the final solution, you may have to use else , as well as in your individual cases.

Also used is $this->redirect(..., false); with the second parameter, thanks lucifurious .

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

Source: https://habr.com/ru/post/1382331/


All Articles