http://blog.sina.com.cn/s/blog_685213e70101mo4i.html
1)首先在model文件夹中新建文件 LoginForm.php 代码如下
<?php
class LoginForm extends CFormModel
{
public $username;
public $password;
public $rememberMe;
private $_identity;
public function rules()
{
return array(
// username and password are required
array('username, password', 'required'),
// rememberMe needs to be a boolean
array('rememberMe', 'boolean'),
// password needs to be authenticated
array('password', 'authenticate'),
);
}
public function attributeLabels()
{
return array(
'rememberMe'=>'Remember me next time',
);
}
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.');
}
}
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;
}
}
2)在controller中添加 public function Login 代码如下
public function actionLogin() {
// set the login page layout
$this->layout = '/layouts/login_page';
$model = new LoginForm;
// if it is ajax validation request
if (isset($_POST['ajax']) && $_POST['ajax'] === 'login-form') {
echo CActiveForm::validate($model);
Yii::app()->end();
}
// collect user input data
if (isset($_POST['LoginForm'])) {
$model->attributes = $_POST['LoginForm'];
// validate user input and redirect to the previous page if valid
if ($model->validate()) {
$user_model = Users::model()->findByAttributes(array('username' => $model->username));
if ($model->login()) {
// Set ip and date attributes to update user record
$attributes = array(
'last_loginip' => ip2long(Yii::app()->request->userHostAddress),
'last_logindate' => date('Y-m-d H:i:s', time()),
);
$this->redirect('index');
}
}
}
// display the login form
$this->render('login', array(
'model' => $model,
));
}
3)编辑protected/component/UserIdentity.php文件 代码如下
<?php
class UserIdentity extends CUserIdentity {
public function authenticate() {
// $users=array(
// // username => password
// 'demo'=>'demo',
// 'admin'=>'admin',
// );
// if(!isset($users[$this->username]))
// $this->errorCode=self::ERROR_USERNAME_INVALID;
// elseif($users[$this->username]!==$this->password)
// $this->errorCode=self::ERROR_PASSWORD_INVALID;
// else
// $this->errorCode=self::ERROR_NONE;
// return !$this->errorCode;
$record = Users::model()->findByAttributes(array('username' => $this->username));
if ($record === null)
$this->errorCode = self::ERROR_USERNAME_INVALID;
else if ($record->password !== $this->password)
$this->errorCode = self::ERROR_PASSWORD_INVALID;
else {