当前位置:首页 > CMS教程 > 其它CMS > 列表

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

发布:smiling 来源: PHP粉丝网  添加日期:2021-07-02 11:34:27 浏览: 评论:0 

这篇文章主要介绍了Yii中实现处理前后台登录的新方法,具体分析了Yii中前后台登录的新思路与相关实现技巧,需要的朋友可以参考下。

本文实例讲述了Yii中实现处理前后台登录的新方法,分享给大家供大家参考,具体如下:

因为最近在做一个项目涉及到前后台登录问题,我是把后台作为一个模块(Module)来处理的。我看很多人放两个入口文件index.php和admin.php,然后分别指向前台和后台。这种方法固然很好,可以将前后台完全分离,但我总觉得这种方式有点牵强,这和两个应用啥区别?还不如做两个App用一个framework更好。而且Yii官方后台使用方法也是使用Module的方式。

但是Moudle的方式有一个很头疼的问题,就是在使用Cwebuser登录时会出现前后台一起登录一起退出的问题,这显然是不合理的。我纠结了很久才找到下文即将介绍的方法,当然,很多也是参考别人的,自己稍作了改动。我一开始的做法是在后台登录时设置一个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.   public function init() 
  4.   { 
  5.     // this method is called when the module is being created 
  6.     // you may place code here to customize the module or the application 
  7.     parent::init();//这步是调用main.php里的配置文件 
  8.     // import the module-level models and componen 
  9.     $this->setImport(array
  10.       'admin.models.*'
  11.       'admin.components.*'
  12.     )); 
  13.     //这里重写父类里的组件 
  14.     //如有需要还可以参考API添加相应组件 
  15.     Yii::app()->setComponents(array
  16.         'errorHandler'=>array
  17.             'class'=>'CErrorHandler'
  18.             'errorAction'=>'admin/default/error'
  19.         ), 
  20.         'admin'=>array
  21.             'class'=>'AdminWebUser',//后台登录类实例 
  22.             'stateKeyPrefix'=>'admin',//后台session前缀 
  23.             'loginUrl'=>Yii::app()->createUrl('admin/default/login'), 
  24.         ), 
  25.     ), false); 
  26.     //下面这两行我一直没搞定啥意思,貌似CWebModule里也没generatorPaths属性和findGenerators()方法 
  27.     //$this->generatorPaths[]='admin.generators'; 
  28.     //$this->controllerMap=$this->findGenerators(); 
  29.   } 
  30.   public function beforeControllerAction($controller$action
  31.   { 
  32.     if(parent::beforeControllerAction($controller$action)) 
  33.     { 
  34.       $route=$controller->id.'/'.$action->id; 
  35.       if(!$this->allowIp(Yii::app()->request->userHostAddress) && $route!=='default/error'
  36.         throw new CHttpException(403,"You are not allowed to access this page."); 
  37.       $publicPages=array
  38.         'default/login'
  39.         'default/error'
  40.       ); 
  41.       if(Yii::app()->admin->isGuest && !in_array($route,$publicPages)) 
  42.         Yii::app()->admin->loginRequired(); 
  43.       else 
  44.         return true; 
  45.     } 
  46.     return false; 
  47.   } 
  48.   protected function allowIp($ip
  49.   { 
  50.     if(emptyempty($this->ipFilters)) 
  51.       return true; 
  52.     foreach($this->ipFilters as $filter
  53.     { 
  54.       if($filter==='*' || $filter===$ip || (($pos=strpos($filter,'*'))!==false && !strncmp($ip,$filter,$pos))) 
  55.         return true; 
  56.     } 
  57.     return false; 
  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.   $keys=array_keys($_SESSION); 
  7.   $prefix=$this->getStateKeyPrefix(); 
  8.   $n=strlen($prefix); 
  9.   foreach($keys as $key
  10.   { 
  11.     if(!strncmp($key,$prefix,$n)) 
  12.       unset($_SESSION[$key]); 
  13.   } 

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

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

差点忘了说明一下:

Yii::app()->user //前台访问用户信息方法

Yii::app()->admin //后台访问用户信息方法

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

附件1:WebUser.php代码:

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

附件2:AdminWebUser.php代码

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

附件3:前台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.    * Authenticates a user. 
  10.    * The example implementation makes sure if the username and password 
  11.    * are both 'demo'. 
  12.    * In practical applications, this should be changed to authenticate 
  13.    * against some persistent user identity storage (e.g. database). 
  14.    * @return boolean whether authentication succeeds. 
  15.    */ 
  16.   public $user
  17.   public $_id
  18.   public $username
  19.   public function authenticate() 
  20.   { 
  21.     $this->errorCode=self::ERROR_PASSWORD_INVALID; 
  22.     $user=User::model()->find('username=:username',array(':username'=>$this->username)); 
  23.      if ($user
  24.     { 
  25.       $encrypted_passwd=trim($user->password); 
  26.       $inputpassword = trim(md5($this->password)); 
  27.       if($inputpassword===$encrypted_passwd
  28.       { 
  29.         $this->errorCode=self::ERROR_NONE; 
  30.         $this->setUser($user); 
  31.         $this->_id=$user->id; 
  32.         $this->username=$user->username; 
  33.         //if(isset(Yii::app()->user->thisisadmin)) 
  34.           // unset (Yii::app()->user->thisisadmin); 
  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->user; 
  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->user=$user->attributes; 
  63.   } 

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

希望本文所述对大家基于Yii框架的PHP程序设计有所帮助。

Tags: Yii后台登录

分享到: