注册成功后自动登录(Yii Framework)

时间:2014-08-22 09:49:45

标签: php yii

我有一份注册表,然后我想在注册成功后自动登录。我已经尝试过了,但注册成功后它并没有自动登录。

这是我的ActionRegister功能:

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,'));
 }

更新和编辑

这是模型LoginForm中的login()函数

   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;
}

这是我的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;
}

}

我的代码有问题吗?我将非常感谢您的帮助和解决方案。

最诚挚的问候。 Rafly。

3 个答案:

答案 0 :(得分:0)

这个适用于我

if ($model->save()) { //If regisrtation success
    $login = new LoginForm;
    $login->username = $_POST['User']['userName'];
    $login->password = $_POST['User']['password'];
    if ($login->validate() && $login->login()) {
        //Redirect home page
    }
}

并确保注册中也没有问题..

答案 1 :(得分:0)

我已经解决了我自己的问题,只需更改authenticate函数的返回值即可

return !$this->errorCode;

答案 2 :(得分:-1)

// your code
    $identity=new LoginForm();
    $identity->username=$model->username;
    $identity->password=$model->password;

//  Try this
    $identity=new LoginForm();
    $identity->username=$model->username;
    $identity->password=$_POST['User']['password'];

在$ model->密码中,您获得加密密码。不是完全密码。

我认为这会起作用

相关问题