Yii中處理先後臺登陸新方法

我一開始的作法是在後臺登陸時設置一個isadmin的session,而後再前臺登陸時註銷這個session,這樣作只能辨別是前臺登陸仍是後臺登陸,但作不到先後臺一塊兒登陸,也即前臺登陸了後臺就退出了,後臺登陸了前臺就退出了。出現這種緣由的根本緣由是咱們使用了同一個Cwebuser實例,不能同時設置先後臺session,要解決這個問題就要將先後臺使用不一樣的Cwebuser實例登陸。下面是個人作法,首先看protected->config->main.php裏對前臺user(Cwebuser)的配置:php

 

[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

 

[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這個數組裏,你能夠打印出來看看)。web

這樣就已經作到了先後臺登陸分離開了,可是此時你退出的話你就會發現先後臺一塊兒退出了。因而我找到了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. }  

 

 

看到沒,就是利用匹配前綴的去註銷的。cookie

到此,咱們就能夠作到先後臺登陸分離,退出分離了。這樣才更像一個應用,是吧?嘿嘿…session

差點忘了說明一下:app

 

[html]  view plain  copy
 
  1. Yii::app()->user//前臺訪問用戶信息方法  
  2. Yii::app()->admin//後臺訪問用戶信息方法  

不懂的仔細看一下剛纔先後臺CWebUser的配置。ide

WebUser.php代碼:ui

 

[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代碼this

 

 

[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. }  
相關文章
相關標籤/搜索