我一开始的做法是在后台登录时设置一个isadmin的session,然后再前台登录时注销这个session,这样做只能辨别是前台登录还是后台登录,但做不到前后台一起登录,也即前台登录了后台就退出了,后台登录了前台就退出了。出现这种原因的根本原因是我们使用了同一个Cwebuser实例,不能同时设置前后台session,要解决这个问题就要将前后台使用不同的Cwebuser实例登录。下面是我的做法,首先看protected->config->main.php里对前台user(Cwebuser)的配置:

  1. 'user'=>array(
  2. 'class'=>'WebUser',//这个WebUser是继承CwebUser,稍后给出它的代码
  3. 'stateKeyPrefix'=>'member',//这个是设置前台session的前缀
  4. 'allowAutoLogin'=>true,//这里设置允许cookie保存登录信息,一边下次自动登录
  5. ),

在你用Gii生成一个admin(即后台模块名称)模块时,会在module->admin下生成一个AdminModule.php文件,该类继承了CWebModule类,下面给出这个文件的代码,关键之处就在该文件,望大家仔细研究:

  1. <?php
  2. class AdminModule extends CWebModule
  3. {
  4. public function init()
  5. {
  6. // this method is called when the module is being created
  7. // you may place code here to customize the module or the application
  8. parent::init();//这步是调用main.php里的配置文件
  9. // import the module-level models and componen
  10. $this->setImport(array(
  11. 'admin.models.*',
  12. 'admin.components.*',
  13. ));
  14. //这里重写父类里的组件
  15. //如有需要还可以参考API添加相应组件
  16. Yii::app()->setComponents(array(
  17. 'errorHandler'=>array(
  18. 'class'=>'CErrorHandler',
  19. 'errorAction'=>'admin/default/error',
  20. ),
  21. 'admin'=>array(
  22. 'class'=>'AdminWebUser',//后台登录类实例
  23. 'stateKeyPrefix'=>'admin',//后台session前缀
  24. 'loginUrl'=>Yii::app()->createUrl('admin/default/login'),
  25. ),
  26. ), false);
  27. //下面这两行我一直没搞定啥意思,貌似CWebModule里也没generatorPaths属性和findGenerators()方法
  28. //$this->generatorPaths[]='admin.generators';
  29. //$this->controllerMap=$this->findGenerators();
  30. }
  31. public function beforeControllerAction($controller, $action){
  32. if(parent::beforeControllerAction($controller, $action)){
  33. $route=$controller->id.'/'.$action->id;
  34. if(!$this->allowIp(Yii::app()->request->userHostAddress) && $route!=='default/error')
  35. throw new CHttpException(403,"You are not allowed to access this page.");
  36. $publicPages=array(
  37. 'default/login',
  38. 'default/error',
  39. );
  40. if(Yii::app()->user->isGuest && !in_array($route,$publicPages))
  41. Yii::app()->user->loginRequired();
  42. else
  43. return true;
  44. }
  45. return false;
  46. }
  47. protected function allowIp($ip)
  48. {
  49. if(empty($this->ipFilters))
  50. return true;
  51. foreach($this->ipFilters as $filter)
  52. {
  53. if($filter==='*' || $filter===$ip || (($pos=strpos($filter,'*'))!==false && !strncmp($ip,$filter,$pos)))
  54. return true;
  55. }
  56. return false;
  57. }
  58. }
  59. ?>

AdminModule 的init()方法就是给后台配置另外的登录实例,让前后台使用不同的CWebUser,并设置后台session前缀,以便与前台session区别开来(他们同事存在$_SESSION这个数组里,你可以打印出来看看)。

这样就已经做到了前后台登录分离开了,但是此时你退出的话你就会发现前后台一起退出了。于是我找到了logout()这个方法,发现他有一个参数$destroySession=true,原来如此,如果你只是logout()的话那就会将session全部注销,加一个false参数的话就只会注销当前登录实例的session了,这也就是为什么要设置前后台session前缀的原因了,下面我们看看设置了false参数的logout方法是如何注销session的:

  1. /**
  2. * Clears all user identity information from persistent storage.
  3. * This will remove the data stored via {@link setState}.
  4. */
  5. public function clearStates()
  6. {
  7. $keys=array_keys($_SESSION);
  8. $prefix=$this->getStateKeyPrefix();
  9. $n=strlen($prefix);
  10. foreach($keys as $key)
  11. {
  12. if(!strncmp($key,$prefix,$n))
  13. unset($_SESSION[$key]);
  14. }
  15. }

看到没,就是利用匹配前缀的去注销的。

到此,我们就可以做到前后台登录分离,退出分离了。这样才更像一个应用,是吧?嘿嘿…

差点忘了说明一下:

  1. Yii::app()->user//前台访问用户信息方法
  2. Yii::app()->admin//后台访问用户信息方法

不懂的仔细看一下刚才前后台CWebUser的配置。

WebUser.php代码:

  1. <?php
  2. class WebUser extends CWebUser
  3. {
  4. public function __get($name)
  5. {
  6. if ($this->hasState('__userInfo')) {
  7. $user=$this->getState('__userInfo',array());
  8. if (isset($user[$name])) {
  9. return $user[$name];
  10. }
  11. }
  12. return parent::__get($name);
  13. }
  14. public function login($identity, $duration) {
  15. $this->setState('__userInfo', $identity->getUser());
  16. parent::login($identity, $duration);
  17. }
  18. }
  19. ?>

AdminWebUser.php代码

  1. <?php
  2. class AdminWebUser extends CWebUser
  3. {
  4. public function __get($name)
  5. {
  6. if ($this->hasState('__adminInfo')) {
  7. $user=$this->getState('__adminInfo',array());
  8. if (isset($user[$name])) {
  9. return $user[$name];
  10. }
  11. }
  12. return parent::__get($name);
  13. }
  14. public function login($identity, $duration) {
  15. $this->setState('__adminInfo', $identity->getUser());
  16. parent::login($identity, $duration);
  17. }
  18. }
  19. ?>

前台UserIdentity.php代码

  1. <?php
  2. /**
  3. * UserIdentity represents the data needed to identity a user.
  4. * It contains the authentication method that checks if the provided
  5. * data can identity the user.
  6. */
  7. class UserIdentity extends CUserIdentity
  8. {
  9. /**
  10. * Authenticates a user.
  11. * The example implementation makes sure if the username and password
  12. * are both 'demo'.
  13. * In practical applications, this should be changed to authenticate
  14. * against some persistent user identity storage (e.g. database).
  15. * @return boolean whether authentication succeeds.
  16. */
  17. public $user;
  18. public $_id;
  19. public $username;
  20. public function authenticate()
  21. {
  22. $this->errorCode=self::ERROR_PASSWORD_INVALID;
  23. $user=User::model()->find('username=:username',array(':username'=>$this->username));
  24. if ($user)
  25. {
  26. $encrypted_passwd=trim($user->password);
  27. $inputpassword = trim(md5($this->password));
  28. if($inputpassword===$encrypted_passwd)
  29. {
  30. $this->errorCode=self::ERROR_NONE;
  31. $this->setUser($user);
  32. $this->_id=$user->id;
  33. $this->username=$user->username;
  34. //if(isset(Yii::app()->user->thisisadmin))
  35. // unset (Yii::app()->user->thisisadmin);
  36. }
  37. else
  38. {
  39. $this->errorCode=self::ERROR_PASSWORD_INVALID;
  40. }
  41. }
  42. else
  43. {
  44. $this->errorCode=self::ERROR_USERNAME_INVALID;
  45. }
  46. unset($user);
  47. return !$this->errorCode;
  48. }
  49. public function getUser()
  50. {
  51. return $this->user;
  52. }
  53. public function getId()
  54. {
  55. return $this->_id;
  56. }
  57. public function getUserName()
  58. {
  59. return $this->username;
  60. }
  61. public function setUser(CActiveRecord $user)
  62. {
  63. $this->user=$user->attributes;
  64. }
  65. }

后台UserIdentity.php代码

  1. <?php
  2. /**
  3. * UserIdentity represents the data needed to identity a user.
  4. * It contains the authentication method that checks if the provided
  5. * data can identity the user.
  6. */
  7. class UserIdentity extends CUserIdentity
  8. {
  9. /**
  10. * Authenticates a user.
  11. * The example implementation makes sure if the username and password
  12. * are both 'demo'.
  13. * In practical applications, this should be changed to authenticate
  14. * against some persistent user identity storage (e.g. database).
  15. * @return boolean whether authentication succeeds.
  16. */
  17. public $admin;
  18. public $_id;
  19. public $username;
  20. public function authenticate()
  21. {
  22. $this->errorCode=self::ERROR_PASSWORD_INVALID;
  23. $user=Staff::model()->find('username=:username',array(':username'=>$this->username));
  24. if ($user)
  25. {
  26. $encrypted_passwd=trim($user->password);
  27. $inputpassword = trim(md5($this->password));
  28. if($inputpassword===$encrypted_passwd)
  29. {
  30. $this->errorCode=self::ERROR_NONE;
  31. $this->setUser($user);
  32. $this->_id=$user->id;
  33. $this->username=$user->username;
  34. // Yii::app()->user->setState("thisisadmin", "true");
  35. }
  36. else
  37. {
  38. $this->errorCode=self::ERROR_PASSWORD_INVALID;
  39. }
  40. }
  41. else
  42. {
  43. $this->errorCode=self::ERROR_USERNAME_INVALID;
  44. }
  45. unset($user);
  46. return !$this->errorCode;
  47. }
  48. public function getUser()
  49. {
  50. return $this->admin;
  51. }
  52. public function getId()
  53. {
  54. return $this->_id;
  55. }
  56. public function getUserName()
  57. {
  58. return $this->username;
  59. }
  60. public function setUser(CActiveRecord $user)
  61. {
  62. $this->admin=$user->attributes;
  63. }
  64. }

Yii中处理前后台登录新方法的更多相关文章

  1. 将dll文件注入到其他进程中的一种新方法

    http://www.45it.com/windowszh/201212/33946.htm http://www.hx95.cn/Article/OS/201212/65095.html 我们知道将 ...

  2. SQL Server中解决死锁的新方法介绍

    SQL Server中解决死锁的新方法介绍 数据库操作的死锁是不可避免的,本文并不打算讨论死锁如何产生,重点在于解决死锁,通过SQL Server 2005, 现在似乎有了一种新的解决办法. 将下面的 ...

  3. Vue中遍历数组的新方法

    1.foreach foreach循环对不能使用return来停止循环 search(keyword){ var newList = [] this.urls.forEach(item =>{ ...

  4. vue学习(十四) 条件搜索框动态查询表中数据 数组的新方法

    //html <div id="app"> <label> 名称搜索关键字: <input type="text" clasa=& ...

  5. Yii中配置单点登录 即多个子站同步登录

    研究Yii的同步登录大概2个多月,几乎查遍了网上所有资料和案例,但都不是很理想,最后摸索出整理出来以下配置方案. 以下配置文件在config.php中,所有需要同步的站点都需要填写.网上一些站点给出的 ...

  6. PHP Laravel 6.2 中用于用户登录的新密码确认流程

    Laravel 发布了 v6.2 版本,它添加了一个新的密码确认功能,该功能使你可以要求已登录的用户重新输入密码,然后才能访问路由. 在你执行敏感操作的时候,这个功能就类似GitHub确认对话框.在 ...

  7. .NET中那些所谓的新语法之二:匿名类、匿名方法与扩展方法

    开篇:在上一篇中,我们了解了自动属性.隐式类型.自动初始化器等所谓的新语法,这一篇我们继续征程,看看匿名类.匿名方法以及常用的扩展方法.虽然,都是很常见的东西,但是未必我们都明白其中蕴含的奥妙.所以, ...

  8. iOS5中UIViewController的新方法

    iOS5中UIViewController的新方法 前言 在苹果的 WWDC2011 大会视频的<Session 101 - What's New in Cocoa> 和<Sessi ...

  9. 实现Square类,让其继承自Rectangle类,并在Square类增添新属性和方法,在2的基础上,在Square类中重写Rectangle类中的初始化和打印方法

    实现Square类,让其继承自Rectangle类,并在Square类增添新属性和方法,在2的基础上,在Square类中重写Rectangle类中的初始化和打印方法 #import <Found ...

随机推荐

  1. php编写的抽奖程序中奖概率算法

    本文给大家分享的是php中奖概率算法,可用于刮刮卡,大转盘等抽奖算法.用法很简单,代码里有详细注释说明,一看就懂,有需要的小伙伴参考下吧. 我们先完成后台PHP的流程,PHP的主要工作是负责配置奖项及 ...

  2. idea通过springboot初始化器新建项目

    1.通过初始化器新建项目,勾选后 对应生成的pom文件 以及生成的包路径 2.生成项目后点击稍后弹出的自动自动导入maven工程的改变,当pom中有依赖改变时会自动刷新导入依赖 3.删除自动生成项目的 ...

  3. 关于ENABLE_BITCODE

    pod 'TSVoiceConverter' 如果,设置了工程target的ENABLE_BITCODE为NO.但是,在真机上运行时,仍然提示类似于如下错误: URGENT: all bitcode ...

  4. QT treewidget 右键菜单

    VS2012+QT5.2 ,没有ui,纯代码实现右键 方法一:常规但略麻烦 1.头文件slot中声明 QTreeWidget *tree; void showrightMenu(QPoint);//显 ...

  5. ECS vs. Kubernetes 类似而又不同

    C2Container Service (ECS)和Kubernetes (K8s) 都解决了同样的问题:跨越主机集群管理容器.ECS和Kubernetes之间的斗争让我想起了vi和Emacs之间的编 ...

  6. C-RAN

    无线接入网(RAN)是移动运营商赖以生存的重要资产.传统的无线接入网具有以下特点: 1. 每一个基站连接若干个固定数量的扇区天线,并覆盖小片区域,每个基站只能处理本小区收发信号: 2. 系统的容量是干 ...

  7. spring的AOP动态代理--JDK代理和CGLIB代理区分以及注意事项

    大家都知道AOP使用了代理模式,本文主要介绍两个代理模式怎么设置以及区别,对原文一些内容进行了引用后加入了自己的理解和更深入的阐述:   一.JDK代理和CGLIB代理的底层实现区别* JDK代理只能 ...

  8. java中HashMap、HashTable、TreeMap的区别总结【表格对比清楚明了】

      底层 有序否 键值对能否为Null 遍历 线程安全 哈希Code Hashmap 数组+链表 无序 都可null iterator 不安全 内部hash方法 Hashtable 数组+链表 无序 ...

  9. VMware 虚拟镜像转 Hyper-V(Win10/2016)

    VMware 虚拟镜像转 Hyper-V(Win10/2016) 参考:http://www.askme4tech.com/how-convert-vmware-virtual-machine-hyp ...

  10. react-quill 富文本编辑器

    适合react的一款轻量级富文本编辑器 1.http://blog.csdn.net/xiaoxiao23333/article/details/62055128 (推荐一款Markdown富文本编辑 ...