我一开始的做法是在后台登录时设置一个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. 20145201《Java程序设计》第8周学习总结

    20145201 <Java程序设计>第八周学习总结 教材学习内容总结 第十五章 通用API 15.1 日志 15.1.1 日志API简介 java.util.logging包提供了日志功 ...

  2. QML、Qt Quick

    当用widget开发Qt时, 语言:C++ 库:Qt库 当用QML开发时, 语言:QML 库:Qt Quick

  3. JS 闭包应用

    1. 代替全局变量 //闭包应用1:代替全局变量的使用 //多个函数都用到一个变量,通常我们会定义一个全局变量,然后在各函数中应用它,//为了避免使用全局变量,可以通过使用立即执行函数定义临时变量,子 ...

  4. linux 安装unrar

    Centos 6 32位下安装 wget http://pkgs.repoforge.org/unrar/unrar-4.2.3-1.el6.rf.i686.rpmrpm -ivh unrar-4.2 ...

  5. Java小程序之输出星号

    题目:打印出如下图案(菱形)     *    ***  ****** ********  ******   ***    * 编程工具使用eclipse 代码如下: package test; pu ...

  6. 腾讯开源手游热更新方案,Unity3D下的Lua编程

    原文:http://www.sohu.com/a/123334175_355140 作者|车雄生 编辑|木环 腾讯最近在开源方面的动作不断:先是微信跨平台基础组件Mars宣布开源,腾讯手游又于近期开源 ...

  7. 分享知识-快乐自己:FastDFS详解

    在使用fdfs之前,需要对其有一定的了解,这篇文章作为准备篇,将针对fdfs的简介,功能性,使用场景等方面进行介绍 一):起源 淘宝网开放平台技术部资深架构师余庆先生首先回顾了自己在Yahoo工作时的 ...

  8. Selenium with Python 002 - 快速入门

    一.简单实例演示 1.创建 python_org_search.py: #!/usr/bin/env python from selenium import webdriver from seleni ...

  9. Django进阶Form篇

    一.django表单系统中,所有的表单类都作为django.forms.Form的之类创建,包括ModelForm 关于django的表单系统,主要分两种: 1.基于django.forms.Form ...

  10. 关于Java类

    一个.java文件中可以有很多类.不过注意以下几点: 1.public 权限的类只能有一个(也可以一个都没有,但最多只有1个) 2.这个.java文件的文件名必须是public类的类名(一般的情况下, ...