本文实例讲述了yii中实现处理前后台登录的新方法。分享给大家供大家参考,具体如下:
因为最近在做一个项目涉及到前后台登录问题,我是把后台作为一个模块(module)来处理的。我看很多人放两个入口文件index.php和admin.php,然后分别指向前台和后台。这种方法固然很好,可以将前后台完全分离,但我总觉得这种方式有点牵强,这和两个应用啥区别?还不如做两个app用一个framework更好。而且yii官方后台使用方法也是使用module的方式。但是moudle的方式有一个很头疼的问题,就是在使用cwebuser登录时会出现前后台一起登录一起退出的问题,这显然是不合理的。我纠结了很久才找到下文即将介绍的方法,当然,很多也是参考别人的,自己稍作了改动。我一开始的做法是在后台登录时设置一个isadmin的session,然后再前台登录时注销这个session,这样做只能辨别是前台登录还是后台登录,但做不到前后台一起登录,也即前台登录了后台就退出了,后台登录了前台就退出了。出现这种原因的根本原因是我们使用了同一个cwebuser实例,不能同时设置前后台session,要解决这个问题就要将前后台使用不同的cwebuser实例登录。下面是我的做法,首先看protected->config->main.php里对前台user(cwebuser)的配置:
'user'=>array( 'class'=>'webuser',//这个webuser是继承cwebuser,稍后给出它的代码 'statekeyprefix'=>'member',//这个是设置前台session的前缀 'allowautologin'=>true,//这里设置允许cookie保存登录信息,一边下次自动登录 ),
在你用gii生成一个admin(即后台模块名称)模块时,会在module->admin下生成一个adminmodule.php文件,该类继承了cwebmodule类,下面给出这个文件的代码,关键之处就在该文件,望大家仔细研究:
<?php
class adminmodule extends cwebmodule
{
public function init()
{
// this method is called when the module is being created
// you may place code here to customize the module or the application
parent::init();//这步是调用main.php里的配置文件
// import the module-level models and componen
$this->setimport(array(
'admin.models.*',
'admin.components.*',
));
//这里重写父类里的组件
//如有需要还可以参考api添加相应组件
yii::app()->setcomponents(array(
'errorhandler'=>array(
'class'=>'cerrorhandler',
'erroraction'=>'admin/default/error',
),
'admin'=>array(
'class'=>'adminwebuser',//后台登录类实例
'statekeyprefix'=>'admin',//后台session前缀
'loginurl'=>yii::app()->createurl('admin/default/login'),
),
), false);
//下面这两行我一直没搞定啥意思,貌似cwebmodule里也没generatorpaths属性和findgenerators()方法
//$this->generatorpaths[]='admin.generators';
//$this->controllermap=$this->findgenerators();
}
public function beforecontrolleraction($controller, $action)
{
if(parent::beforecontrolleraction($controller, $action))
{
$route=$controller->id.'/'.$action->id;
if(!$this->allowip(yii::app()->request->userhostaddress) && $route!=='default/error')
throw new chttpexception(403,"you are not allowed to access this page.");
$publicpages=array(
'default/login',
'default/error',
);
if(yii::app()->admin->isguest && !in_array($route,$publicpages))
yii::app()->admin->loginrequired();
else
return true;
}
return false;
}
protected function allowip($ip)
{
if(empty($this->ipfilters))
return true;
foreach($this->ipfilters as $filter)
{
if($filter==='*' || $filter===$ip || (($pos=strpos($filter,'*'))!==false && !strncmp($ip,$filter,$pos)))
return true;
}
return false;
}
}
?>
adminmodule 的init()方法就是给后台配置另外的登录实例,让前后台使用不同的cwebuser,并设置后台session前缀,以便与前台session区别开来(他们同事存在$_session这个数组里,你可以打印出来看看)。
这样就已经做到了前后台登录分离开了,但是此时你退出的话你就会发现前后台一起退出了。于是我找到了logout()这个方法,发现他有一个参数$destroysession=true,原来如此,如果你只是logout()的话那就会将session全部注销,加一个false参数的话就只会注销当前登录实例的session了,这也就是为什么要设置前后台session前缀的原因了,下面我们看看设置了false参数的logout方法是如何注销session的:
/**
* clears all user identity information from persistent storage.
* this will remove the data stored via {@link setstate}.
*/
public function clearstates()
{
$keys=array_keys($_session);
$prefix=$this->getstatekeyprefix();
$n=strlen($prefix);
foreach($keys as $key)
{
if(!strncmp($key,$prefix,$n))
unset($_session[$key]);
}
}
看到没,就是利用匹配前缀的去注销的。
到此,我们就可以做到前后台登录分离,退出分离了。这样才更像一个应用,是吧?嘿嘿…
差点忘了说明一下:
yii::app()->user //前台访问用户信息方法 yii::app()->admin //后台访问用户信息方法
不懂的仔细看一下刚才前后台cwebuser的配置。
附件1:webuser.php代码:
<?php
class webuser extends cwebuser
{
public function __get($name)
{
if ($this->hasstate('__userinfo')) {
$user=$this->getstate('__userinfo',array());
if (isset($user[$name])) {
return $user[$name];
}
}
return parent::__get($name);
}
public function login($identity, $duration) {
$this->setstate('__userinfo', $identity->getuser());
parent::login($identity, $duration);
}
}
?>
附件2:adminwebuser.php代码
<?php
class adminwebuser extends cwebuser
{
public function __get($name)
{
if ($this->hasstate('__admininfo')) {
$user=$this->getstate('__admininfo',array());
if (isset($user[$name])) {
return $user[$name];
}
}
return parent::__get($name);
}
public function login($identity, $duration) {
$this->setstate('__admininfo', $identity->getuser());
parent::login($identity, $duration);
}
}
?>
附件3:前台useridentity.php代码
<?php
/**
* useridentity represents the data needed to identity a user.
* it contains the authentication method that checks if the provided
* data can identity the user.
*/
class useridentity extends cuseridentity
{
/**
* authenticates a user.
* the example implementation makes sure if the username and password
* are both 'demo'.
* in practical applications, this should be changed to authenticate
* against some persistent user identity storage (e.g. database).
* @return boolean whether authentication succeeds.
*/
public $user;
public $_id;
public $username;
public function authenticate()
{
$this->errorcode=self::error_password_invalid;
$user=user::model()->find('username=:username',array(':username'=>$this->username));
if ($user)
{
$encrypted_passwd=trim($user->password);
$inputpassword = trim(md5($this->password));
if($inputpassword===$encrypted_passwd)
{
$this->errorcode=self::error_none;
$this->setuser($user);
$this->_id=$user->id;
$this->username=$user->username;
//if(isset(yii::app()->user->thisisadmin))
// unset (yii::app()->user->thisisadmin);
}
else
{
$this->errorcode=self::error_password_invalid;
}
}
else
{
$this->errorcode=self::error_username_invalid;
}
unset($user);
return !$this->errorcode;
}
public function getuser()
{
return $this->user;
}
public function getid()
{
return $this->_id;
}
public function getusername()
{
return $this->username;
}
public function setuser(cactiverecord $user)
{
$this->user=$user->attributes;
}
}
附件4:后台useridentity.php代码
<?php
/**
* useridentity represents the data needed to identity a user.
* it contains the authentication method that checks if the provided
* data can identity the user.
*/
class useridentity extends cuseridentity
{
/**
* authenticates a user.
* the example implementation makes sure if the username and password
* are both 'demo'.
* in practical applications, this should be changed to authenticate
* against some persistent user identity storage (e.g. database).
* @return boolean whether authentication succeeds.
*/
public $admin;
public $_id;
public $username;
public function authenticate()
{
$this->errorcode=self::error_password_invalid;
$user=staff::model()->find('username=:username',array(':username'=>$this->username));
if ($user)
{
$encrypted_passwd=trim($user->password);
$inputpassword = trim(md5($this->password));
if($inputpassword===$encrypted_passwd)
{
$this->errorcode=self::error_none;
$this->setuser($user);
$this->_id=$user->id;
$this->username=$user->username;
// yii::app()->user->setstate("thisisadmin", "true");
}
else
{
$this->errorcode=self::error_password_invalid;
}
}
else
{
$this->errorcode=self::error_username_invalid;
}
unset($user);
return !$this->errorcode;
}
public function getuser()
{
return $this->admin;
}
public function getid()
{
return $this->_id;
}
public function getusername()
{
return $this->username;
}
public function setuser(cactiverecord $user)
{
$this->admin=$user->attributes;
}
}
希望本文所述对大家基于yii框架的php程序设计有所帮助。
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:)!