Halo, I have tried to do a login activity in Yii with database. I think I didn’t make mistake in my program, but when I input the username and password, the application does nothing but redirect to the Homepage without I logged in. I have tried to override the $_id, but still same. I hope anyone can teach me how can I fix it. Thanks all.
So, here’s my code:
- The UserIdentity.php
class UserIdentity extends CUserIdentity
{
private $_id;
public function authenticate()
{
$user = User::model()->findByAttributes(array('username'=>$this->username));
if ($user===null) {
$this->errorCode=self::ERROR_USERNAME_INVALID;
}
else if ($user->password !== md5($this->password) ) {
$this->errorCode=self::ERROR_PASSWORD_INVALID;
}
else { // Okay!
$this->errorCode=self::ERROR_NONE;
}
return !$this->errorCode;
}
public function getId() // override Id
{
return $this->_id;
}
}
- SiteController.php
public function actionLogin()
{
{
$model=new LoginForm;
if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
if(isset($_POST['LoginForm']))
{
$model->attributes=$_POST['LoginForm'];
// validate user input and redirect to the previous page if valid
if($model->validate() && $model->login())
{
$this->redirect(array("index"));
}
}
$this->render('login',array('model'=>$model));
}
}
- authenticate function in LoginForm.php
public function authenticate($attribute,$params)
{
if(!$this->hasErrors())
{
$this->_identity=new UserIdentity($this->username,$this->password);
if(!$this->_identity->authenticate())
$this->addError('password','Incorrect username or password.');
}
}