详解yii用户登录体系

二登录验证
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);
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值