參考連結(原文有錯,本文已更正)
預設的表結構:
CREATE TABLE tbl_user ( id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT, username VARCHAR(128) NOT NULL, password VARCHAR(128) NOT NULL, email VARCHAR(128) NOT NULL);
User.php(路徑 models/) 添加如下加密方法
/** * @return boolean validate user */public function validatePassword($password, $username){ return $this->hashPassword($password, $username) === $this->password;}/** * @return hashed value */public function hashPassword($phrase, $salt = null){ DEFINE('SALT_LENGTH', 10); $key = 'Gf;B&yXL|beJUf-K*PPiU{wf|@9K9j5?d+YW}?VAZOS%e2c -:11ii<}ZM?PO!96'; if($salt == '') $salt = substr(hash('sha512', $key), 0, SALT_LENGTH); else $salt = substr($salt, 0, SALT_LENGTH); return hash('sha512', $salt . $key . $phrase);}
UserController.php(路徑 controllers) 更改其中的方法如下(參考連結原文中有錯)
/** * Creates a new model. * If creation is successful, the browser will be redirected to the 'view' page. */public function actionCreate(){ $model=new User; // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); if(isset($_POST['User'])) { $model->attributes=$_POST['User']; $model->password = $model->hashPassword($_POST['User']['password'], $_POST['User']['username']); if($model->save()) $this->redirect(array('view','id'=>$model->id)); else $model->password = $_POST['User']['password']; } $this->render('create',array( 'model'=>$model, ));}
更改"UserIdentity.php"(路徑components)如下
public function authenticate(){ $username = $this->username; $user = User::model()->find('username=?', array($username)); if($user === NULL) $this->errorCode=self::ERROR_USERNAME_INVALID; else if(!$user->validatePassword($this->password, $this->username)) $this->errorCode=self::ERROR_PASSWORD_INVALID; else{ $this->username = $user->username; $this->errorCode=self::ERROR_NONE; } return !$this->errorCode;}
完