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'),
),