╃巡洋艦㊣ 2011-02-28 10:24:29 6973次浏览 6条回复 5 0 0

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'),
),
您需要登录后才可以回复。登录 | 立即注册