Automatically Login After Registration Success

I have a registration form, then I want to do an automatic login after the registration is successful. I already tried it, but it doesn’t automatically login after a successful registration.

This is my ActionRegister function:




public function actionRegister(){


   $model = new User;


 if(isset($_POST['User'])){

    $model->username = $_POST['User']['username'];

    $model->password = $model->hashPassword($_POST['User']['password']);

    $model->email = $_POST['User']['email'];


    $identity=new LoginForm();

    $identity->username=$model->username;

    $identity->password=$model->password;


 if($model->save()) {

    $identity->login();

    $this->redirect(array('index'));

    } 

 } 

     $this->render('register',array('model'=>$model,'));

 }




this is my login() function in model LoginForm




   public function login()

   {

    if($this->_identity===null)

    {

        $this->_identity=new UserIdentity($this->username,$this->password);

        $this->_identity->authenticate();

    }

    if($this->_identity->errorCode===UserIdentity::ERROR_NONE)

    {

        $duration=$this->rememberMe ? 3600*24*30 : 0; // 30 days

        Yii::app()->user->login($this->_identity,$duration);

        return true;

    }

    else

        return false;

}



and this is my UserIdentity.php




  class UserIdentity extends CUserIdentity

  {

  private $_id;

  private $level;


  public function authenticate()

  {

  $record=user::model()->findByAttributes(array('username'=>$this->username));

  if($record===null)

   $this->errorCode=self::ERROR_USERNAME_INVALID;

  else if($record->password!==md5($this->password))

   $this->errorCode=self::ERROR_PASSWORD_INVALID; 


  else

 { 

 $this->_id=$record->id;

 $this->username=$record->username;

 $this->errorCode=self::ERROR_NONE;

 }


 return $this->errorCode==self::ERROR_NONE;

 }


public function getId(){

return $this->_id;

}


}



Is there any problem in my code? I’ll appreciate any of your help and solution.

Best Regards.

:)

Hello flashzapper,

try this in your class UserIdentity , class Login authenticate function requires 1 to be a valid user


return !$this->errorCode;

Thanks bro , it’s worked !

:)