Yii Framework的用戶驗證與授權
yii提供了CUserIdentity類,這個類一般用於驗證用戶名和密碼的類.繼承後我們需要重寫其中的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;
}
}
在用戶登陸時則調用如下代碼:
// 使用提供的用戶名和密碼登錄用戶
if($identity->authenticate())
Yii::app()->user->login($identity);
else
echo $identity->errorMessage;
用戶退出時,則調用如下代碼:
// 註銷當前用戶Yii::app()->user->logout();
其中的user是yii的一個components.需要在protected/config/main.php中定義'user'=>array(
// enable cookie-based authentication
'allowAutoLogin'=>true,
'loginUrl' => array('site/login'),
),