详解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 PHP Framework实用入门教程(详细介绍)
- Yii操作数据库的3种方法
- 在yii中新增一个用户验证的方法详解
- Yii框架在页面输出执行sql语句以方便调试的实现方法
- 浅析Yii中使用RBAC的完全指南(用户角色权限控制)
- yii中widget的用法
- Yii实现自动加载类地图的方法
- Yii配置文件用法详解
- yiic命令时提示“php.exe”不是内部或外部命令的解决方法
- Yii扩展组件编写方法实例分析
- Yii获取当前url和域名的方法
- Yii核心组件AssetManager原理分析
- yii操作session实例简介
- Yii使用ajax验证显示错误messagebox的解决方法
- Yii中使用PHPExcel导出Excel的方法
- Yii入门教程之Yii安装及hello world
- Yii学习总结之安装配置
- yii实现图片上传及缩略图生成的方法
- yii实现创建验证码实例解析
- Yii调试SQL的常用方法