以資料庫驗證登入

由於 Yii 內定的原始框架程式, 採用綁定在UserIdentity.php 的 demo 與 admin 帳號密碼:

public function authenticate()
{
$users=array(
// username => password
'demo'=>'demo',
'admin'=>'admin',
);



而一般的網際程式都希望能夠利用特定的 User 資料表中的帳號與密碼來進行登入驗證, 因此必須進行如下修改:

component\UserIdentity.php 中的

public function authenticate()
{
// 根據使用者所輸入的 $this->username 在 User model 中(即對應資料表 user), 搜尋對應的
// 用戶名稱
$user=User::model()->find('LOWER(username)=?',array(strtolower($this->username)));
// 假如查無此帳號, 則回覆錯誤
if($user===null)
$this->errorCode=self::ERROR_USERNAME_INVALID;
// 若密碼不符, 也是回覆錯誤
else if(!$user->validatePassword($this->password))
$this->errorCode=self::ERROR_PASSWORD_INVALID;
else
{
// 順利登入
$this->_id=$user->id;
$this->username=$user->username;
$this->errorCode=self::ERROR_NONE;
}
return $this->errorCode==self::ERROR_NONE;
}



用來利用資料表 user 驗證使用者登入. 

在 User.php Model 中還需要:

/**
* Generates a salt that can be used to generate a password hash.
* @return string the salt
*/
protected function generateSalt()
{
return uniqid('',true);
}


截至目前為止, 已經完成下列事項:

  1. Yii 系統已經正確安裝, framework 目錄位於 www 目錄之外.
  2. Blog 骨架程式已經建立.
  3. Blog 系統所需要的 SQLite 資料表已經建立.
  4. main.php 中的資料連結設定已經配合更改.
  5. 與資料表對應的 model 與 CRUD 運作程式已經建立.
  6. 使用者登入的驗證, 已經由原先的內定帳號密碼, 改為經由 tbl_user 資料表進行驗證.