您的位置:首页 > 编程语言 > PHP开发

详解yii用户登录体系

2015-08-14 15:09 791 查看

登录验证

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();


三CWebuser记录session的值

在验证用户名和密码成功后yii调用cwebuser的login方法

login($identity,$duration=0)
{
$id=$identity->getId();
$states=$identity->getPersistentStates();
if($this->beforeLogin($id,$states,false))
{
$this->changeIdentity($id,$identity->getName(),$states);

if($duration>0)
{
if($this->allowAutoLogin)
$this->saveToCookie($duration);
else
throw new CException(Yii::t('yii','{class}.allowAutoLogin must be set true in order to use cookie-based authentication.',
array('{class}'=>get_class($this))));
}

$this->afterLogin(false);
}
}


在changeIdentity方法中调用了:

$this->setId($id);--
$this->setName($name);--
//分别将__id和__name保存到session中
public function setState($key,$value,$defaultValue=null)
{
$key=$this->getStateKeyPrefix().$key;//获取app的编号
if($value===$defaultValue)
unset($_SESSION[$key]);
else
$_SESSION[$key]=$value;
}

$this->loadIdentityStates($states);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  yii