我不知道为什么authenticate()在这个简单的例子中不起作用:
这是我用户表
中的一条记录
模型/ user.php的
class User extends CActiveRecord
{
public $id;
public $name;
public $lastname;
public $login;
public $password;
public $date;
public static function model($className = __CLASS__)
{
return parent::model($className);
}
public function tableName()
{
return 'user';
}
public function attributeLabels()
{
return array(
'id' => 'ID',
'name' => 'Imię',
'lastname' => 'Nazwisko',
'login' => 'Login',
'password' => 'Hasło',
'date' => 'Data rejestracji',
);
}
public function rules()
{
return array(
array('name','required'),
array('lastname','required'),
array('login','required'),
array('password','required'),
array('date','default',
'value'=>new CDbExpression('NOW()'),
'setOnEmpty'=>false,'on'=>'insert')
);
}
}
模型/ UserIdentity.php
class UserIdentity extends CUserIdentity
{
private $_id;
public function authenticate()
{
$record = user::model()->findAllByAttributes(array('login' => $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->errorCode = self::ERROR_NONE;
}
return !$this->errorCode;
}
public function getId()
{
return $this->_id;
}
}
控制器/ UserController.php
[...]
public function actionLogin()
{
$username = 'janek';
$password = '1234';
$identity=new UserIdentity($username,$password);
if($identity->authenticate())
{
echo $identity;
}
else
{
echo "NOT OK";
}
}
[...]
当请求操作登录时,总是显示NOT OK。我修改了yii doc的例子。
答案 0 :(得分:0)
The problem is that the password in your database is not encrypted, according to the data you presented.
In this case, rewrite your check as
else if($record->password !== $this->password)
instead of
else if($record->password !== md5($this->password))
You should however, be saving your password in an encrypted manner. Of the many options, using md5 is not generally regarded as a safe option. Have a look at the official Yii documentation that shows how to use the Password helper library. http://www.yiiframework.com/doc/guide/1.1/en/topics.auth