Yii 登录验证依靠两个类
1.CUserIdentity(实现基于用户名和密码的验证) 文件地址:/web/auth/CUserIdentity.php
2.CWebUser(储存用户的持久身份信息) 文件地址:
首先在config/main.php配置components
'user'=>array(
// enable cookie-based authentication
'allowAutoLogin'=>true,
),
<pre name="code" class="php"> 'admin'=>array(
'allowAutoLogin'=>true,
),
上述备注中,创建了user和admin 组件,在操作中可以根据需求,要选择哪个组件
例:Yii::app()->user->login($identity)
Yii::app()->admin->login($identity)
注:1.$identity为CUserIdentity
CUserIdentity源码
<?php
class CUserIdentity extends CBaseUserIdentity
{
public $username;
public $password;
public function __construct($username,$password){
$this->username=$username;
$this->password=$password;
}
public function authenticate(){//继承后复写
//验证规则,通过用户名和密码进行数据库操作,验证
}
public function getId(){//返回用户ID 继承后复写
return $this->username;
}
public function getName(){
return $this->username;
}
}
components UserIdentity 继承复写:
class UserIdentity extends CUserIdentity
{
public function authenticate(){//复写验证方法
if($this->username=='xxxx' && $this->password=='xxx'){
return true;
}
else{
return false;
}
}
public function getId(){//返回用户ID
return 3;//根据数据查出的结果返回
}
}
创建UserController,包含三个动作 actionIndex、actionLogin、actionLogout
<?php
class UserController extends Controller{
public function actionIndex(){
echo "Index--".Yii::app()->user->name;
}
public function actionLogout(){//退出
Yii::app()->user->logout();
}
public function actionLogin(){//登录
$identity=new UserIdentity("username","password");
$result=$identity->authenticate();//验证
if($result){
Yii::app()->user->login($identity);
$this->redirect(array('user/index'));//跳转
}
}
}
?>
注: 1.在user->login 之前Yii::app()->user->isGuest 为 true, 之后为 false(代表已经登录)
2.访问r=user/login
3.在user->login($identity)之后, user对象将会保存两个属性 name,id
获取方法:Yii::app()->user->name Yii::app()->user->id;
4.Yii::app()->user->setState(key,value)。可以设置新的键值存储
5.Yii::app()->user->getState(key).获取键值
6.Yii::app()->user->hasState(key) 判断是否存在键