Yii中处理前后台登录新方法
我一开始的做法是在后台登录时设置一个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()->user->isGuest && !in_array($route,$publicPages))
- Yii::app()->user->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的配置。
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);
- }
- }
- ?>
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);
- }
- }
- ?>
前台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;
- }
- }
后台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中处理前后台登录新方法的更多相关文章
- 将dll文件注入到其他进程中的一种新方法
http://www.45it.com/windowszh/201212/33946.htm http://www.hx95.cn/Article/OS/201212/65095.html 我们知道将 ...
- SQL Server中解决死锁的新方法介绍
SQL Server中解决死锁的新方法介绍 数据库操作的死锁是不可避免的,本文并不打算讨论死锁如何产生,重点在于解决死锁,通过SQL Server 2005, 现在似乎有了一种新的解决办法. 将下面的 ...
- Vue中遍历数组的新方法
1.foreach foreach循环对不能使用return来停止循环 search(keyword){ var newList = [] this.urls.forEach(item =>{ ...
- vue学习(十四) 条件搜索框动态查询表中数据 数组的新方法
//html <div id="app"> <label> 名称搜索关键字: <input type="text" clasa=& ...
- Yii中配置单点登录 即多个子站同步登录
研究Yii的同步登录大概2个多月,几乎查遍了网上所有资料和案例,但都不是很理想,最后摸索出整理出来以下配置方案. 以下配置文件在config.php中,所有需要同步的站点都需要填写.网上一些站点给出的 ...
- PHP Laravel 6.2 中用于用户登录的新密码确认流程
Laravel 发布了 v6.2 版本,它添加了一个新的密码确认功能,该功能使你可以要求已登录的用户重新输入密码,然后才能访问路由. 在你执行敏感操作的时候,这个功能就类似GitHub确认对话框.在 ...
- .NET中那些所谓的新语法之二:匿名类、匿名方法与扩展方法
开篇:在上一篇中,我们了解了自动属性.隐式类型.自动初始化器等所谓的新语法,这一篇我们继续征程,看看匿名类.匿名方法以及常用的扩展方法.虽然,都是很常见的东西,但是未必我们都明白其中蕴含的奥妙.所以, ...
- iOS5中UIViewController的新方法
iOS5中UIViewController的新方法 前言 在苹果的 WWDC2011 大会视频的<Session 101 - What's New in Cocoa> 和<Sessi ...
- 实现Square类,让其继承自Rectangle类,并在Square类增添新属性和方法,在2的基础上,在Square类中重写Rectangle类中的初始化和打印方法
实现Square类,让其继承自Rectangle类,并在Square类增添新属性和方法,在2的基础上,在Square类中重写Rectangle类中的初始化和打印方法 #import <Found ...
随机推荐
- 学习笔记1126 - Fib的计算方法,降低了时间复杂度
#include <stdio.h> #include <stdlib.h> #define NUM 10 //如果NUM很大的话,应该申请的动态内存要用long类型吧? in ...
- uiautomator--图像处理
一.图像处理在自动化中使用场景 1)效果类截图 图像处理技术在自动化的场景中很容易使用到.自动化不是万能的,有时候效果类的是无法进行验证的,但是效果类一般会有图像显示,我们可以通过截图对比实现. 2 ...
- QMesageBox的使用
一.使用构造函数弹出对话框 1. QMessageBox msgBox://最简单的对话框,里面什么也没有 QString str = “test”: msgBox.setText(str); msg ...
- xml的servlet配置
内容如下 <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="ht ...
- nagios无法载入静态资源
使用nginx+nagios无法载入静态资源,看了下url中增加了一个/nagios 查看是/usr/local/nagios/etc/cgi.conf中url_html_path=/nagios 将 ...
- HIVE- SCD缓慢变化
SCD缓慢变化维,比如一个用户维表,用户属性会变化,但是不会变化很剧烈,可能一年只会变化一两次,也不会所有用户的属性都会有变化,只有少量的数据发生变化,所以叫缓慢变化维.这种问题就是由于维度的变化所造 ...
- LeetCode第[1]题(Java):Two Sum (俩数和为目标数的下标)——EASY
题目: Given an array of integers, return indices of the two numbers such that they add up to a specifi ...
- 栈的基本操作--java实现
package com.wyl.linklist; /** * 栈的定义及相关操作 * 用数组实现栈 * 栈是一个线性表,不过进栈和出栈操作在表尾操作 * @author wyl * */ publi ...
- linux安装-----源码安装步骤--zlib软件安装
该zlib 可以对许多其他软件的编译代码起着优化 压缩作用. 解压压缩包: .tar.gz------------->tar zxvf 压缩包.tar.gz .tar.bz2---------- ...
- 智课雅思词汇---二十四、名词性后缀ary(也是形容词后缀)
智课雅思词汇---二十四.名词性后缀ary(也是形容词后缀) 一.总结 一句话总结:很多词缀即是名词词缀也是形容词词缀,很多词即是名词也是形容词 1.名词性后缀-tude? 词根词缀:-tude [来 ...