Yii Framework的用户验证与授权

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;
    }

在用户登陆时则调用如下代码:

// 使用提供的用户名和密码登录用户

$identity=new UserIdentity($username,$password);
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'),
),

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章