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

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

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

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

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

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

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

[html] view plain copy
 
  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. }  

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

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

差点忘了说明一下:

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

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

WebUser.php代码:

[html] view plain copy
 
  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.   
  13.         return parent::__get($name);  
  14.     }  
  15.   
  16.     public function login($identity, $duration) {  
  17.         $this->setState('__userInfo', $identity->getUser());  
  18.         parent::login($identity, $duration);  
  19.     }  
  20. }  
  21.   
  22. ?>  


AdminWebUser.php代码

[html] view plain copy
 
  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.   
  13.         return parent::__get($name);  
  14.     }  
  15.   
  16.     public function login($identity, $duration) {  
  17.         $this->setState('__adminInfo', $identity->getUser());  
  18.         parent::login($identity, $duration);  
  19.     }  
  20. }  
  21.   
  22. ?>  


前台UserIdentity.php代码

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


后台UserIdentity.php代码

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

 

原文地址:https://www.cnblogs.com/rainblack/p/5632489.html