二登录验证
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);
转载于:https://www.cnblogs.com/iplus/archive/2012/04/19/4489988.html