我一开始的做法是在后台登录时设置一个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. }

最新文章

  1. 实现bootstrap布局的input输入框中的图标点击功能
  2. Android实现下滑和上滑事件
  3. JSP前三章错题整理
  4. JavaScript:最烂与最火
  5. shell 之for [转]
  6. Ubuntu12.04配置静态ip地址
  7. 系统集成之用户统一登录( LDAP + wso2 Identity Server)
  8. Elasticsearch学习笔记
  9. [转载]C++异常机制的实现方式和开销分析
  10. Atom编辑器入门到精通(六) Markdown支持
  11. TransactionScrope 2
  12. python中关于字符串的操作
  13. Websphere(was)与Weblogic部署EJB的注意项
  14. Kylin与CDH兼容性剖析
  15. Treap标准模板
  16. Python自定义Module中__init__.py文件介绍
  17. 提交JSON修改数据
  18. Socket网络编程--小小网盘程序(5)
  19. yum下载rpm包
  20. js 捕获浏览器后退事件

热门文章

  1. BeatSaber节奏光剑双手柄MR教程
  2. unidbnavigator提示汉化
  3. JVM 深入浅出
  4. tensorflow conv2d的padding解释以及参数解释
  5. 第11章:最长公共子序列(LCS:Longest Common Subsequence)
  6. 在js中,ajax放在for中,ajax获取得到的变量有误
  7. java处理HTTP请求
  8. serialVersionUID 作用
  9. docker的应用
  10. HTML 中 id与name 区别