首页 > 开发 > PHP > 正文

Yii中实现处理前后台登录的新方法

2024-05-04 22:33:07
字体:
来源:转载
供稿:网友

本文实例讲述了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类,下面给出这个文件的代码,关键之处就在该文件,望大家仔细研究:

<?phpclass 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;  }}?>            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表