I have just started messing about with yii and I’m trying to implementing registration. I’ve managed to add login details to database but can’t login automatically afterwards my register controller:
if($_POST['register'])
{
$user=new User();
$user->attributes=$_POST['register'];
if($user->validate())
{
$user->save();
$identity=new UserIdentity($username,$password);
if($identity->authenticate())
$duration= 3600*24*30;
Yii::app()->user->login($identity,$duration);
$json = array('redirect'=>Yii::app()->request->baseUrl.'/profile/index');
echo CJSON::encode($json);
exit();
}
else
{
$data['error'] = $user->getErrors();
echo CJSON::encode($data);
exit();
}
in my useridentity class:
private $_id;
public function authenticate()
{
$record=User::model()->findByAttributes(array('username'=>$this->username));
if($record===null)
$this->errorCode=self::ERROR_USERNAME_INVALID;
else if($record->password!==sha1($this->password.md5($this->username)))
$this->errorCode=self::ERROR_PASSWORD_INVALID;
else
{
$this->_id=$record->id;
$this->errorCode=self::ERROR_NONE;
}
return !$this->errorCode;
}
public function getId()
{
return $this->_id;
}
I’m also using this in my user model:
public function beforeSave() {
$this->password = sha1($this->password.md5($this->username));
return true;
}
Any ideas?