注意:Yii默認的代碼,Yii::app()->user->id返回的不是我們想要的用戶ID,而是用戶名。因此在useridentity類中要用一個變量來存儲登錄用戶的ID,然后重載getID()方法,返回正確的用戶ID。
Yii 有一個內置的驗證/授權(auth)框架,用起來很方便,還能對其進行自定義,使其符合特殊的需求。
Yii auth 框架的核心是一個預定義的 用戶(user)應用組件 它是一個實現了 IWebUser 接口的對象。此用戶組件代表當前用戶的持久性認證信息。我們可以通過Yii::app()->user
在任何地方訪問它。
使用此用戶組件,我們可以通過 CWebUser::isGuest 檢查檢查一個用戶是否登陸; 可以 登錄(login) 或 注銷(logout) 一個用戶;我們可以通過CWebUser::checkAccess檢查此用戶是否可以執行特定的操作;還可以獲取此用戶的唯一標識(unique identifier)及其他持久性身份信息。
為了驗證一個用戶,我們定義一個有驗證邏輯的身份類。這個身份類實現IUserIdentity 接口。
不同的類可能實現不同的驗證方式(例如:OpenID,LDAP)。最好是繼承 CUserIdentity,此類是居於用戶名和密碼的驗證方式。
定義身份類的主要工作是實現IUserIdentity::authenticate方法。在用戶會話中根據需要,身份類可能需要定義別的身份信息。
下面是個例子:
class UserIdentity extends CUserIdentity { private $_id; public function authenticate() { $record=User::model()->findByAttributes(array('username'=>$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->setState('title', $record->title); $this->errorCode=self::ERROR_NONE; } return !$this->errorCode; } public function getId() { return $this->_id; } }
二、自己的操作
路徑
<?php /** * UserIdentity represents the data needed to identity a user. * It contains the authentication method that checks if the provided * data can identity the user. */ class UserIdentity extends CUserIdentity { private $_id; /** * Authenticates a user. * The example implementation makes sure if the username and password * are both 'demo'. * In practical applications, this should be changed to authenticate * against some persistent user identity storage (e.g. database). * @return boolean whether authentication succeeds. */ public function authenticate() { $userInfo = Admin::model()->find('username=:name', array(':name'=>$this->username)); if($userInfo == NULL){ $this->errorCode=self::ERROR_USERNAME_INVALID; return false; } if($userInfo->password !== md5($this->password)){ $this->errorCode=self::ERROR_PASSWORD_INVALID; return false; } $this->_id = $userInfo->admin_id; $this->errorCode=self::ERROR_NONE; return true; /* $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;*/ } public function getId() { return $this->_id; } }