yiii 框架登錄 判斷是否是游客模式及未登錄狀態


原地址:http://blog.csdn.net/a553181867/article/details/50987388

 

最近在利用Yii 2.0框架進行項目后台的編寫,遇到的第一個問題是用戶登陸,包括利用cookie,session登陸等等,筆者從源碼角度結合實例為各位詳細解析如何編寫一個完整的用戶登陸模塊。(筆者的本地環境是PHP 5.5+MySQL5.6) 


一、准備

在 開始編寫代碼之前,我們需要思考一下:用戶登陸模塊,實現的是什么功能?很明顯,是登陸功能,那么,登陸需要用戶名和密碼,我們在數據庫的一張表中就應該 准備好用戶名和密碼的字段,再思考一下,如果要實現自動登陸的功能,那么還需要什么?Cookie,是專門用於自動登陸的,所以,我們的數據表可能需要准 備一個字段,專門用於儲存客戶端登陸所生成的cookie,這樣,就能通過驗證客戶端和服務端的cookie是否相同來進行自動登陸了。基於以上思考,我 們的數據表應該包含以下字段:
id(primarykey,auto_increment),username(varchar),password(varchar(32)),auth_key(varchar(32)),accessToken(varchar(32))(這個暫不解釋,后文解釋).
     1、首先,建立一個數據庫:myDatabase,
     2、然后建立一張數據表:user,增加上述字段。
     對於如何建數據庫和建表,這里不再贅述。

二、模型(Model)

Yii框架采用MVC設計模式,所以Model是一個模塊的核心所在,所以我們先完成對Model的編寫。


      1、LoginForm.php

用戶登陸模塊,所提交的是username和password,所以我們要先建立一個Model,專門處理用戶提交的數據,所以先新建一個LoginForm.php,以下為代碼:

 

  1. <?php  
  2.   
  3. namespace app\modules\backend\models;  
  4.   
  5. use Yii;  
  6. use yii\base\Model;  
  7.   
  8. /** 
  9.  * LoginForm is the model behind the login form. 
  10.  */  
  11. class LoginForm extends Model  
  12. {  
  13.     public $username;  
  14.     public $password;  
  15.     public $rememberMe = true;  
  16.   
  17.     private $_user = false;  
  18.   
  19.   
  20.     /** 
  21.      * @return array the validation rules. 
  22.      */  
  23.     public function rules()<span style="white-space:pre">     </span>//①  
  24.     {  
  25.         return [  
  26.             // username and password are both required  
  27.             [['username', 'password'], 'required','message'=>""],  
  28.             // rememberMe must be a boolean value  
  29.             ['rememberMe', 'boolean'],  
  30.             // password is validated by validatePassword()  
  31.             ['password', 'validatePassword'],  
  32.         ];  
  33.     }  
  34.   
  35.     /** 
  36.      * Validates the password. 
  37.      * This method serves as the inline validation for password. 
  38.      * 
  39.      * @param string $attribute the attribute currently being validated 
  40.      * @param array $params the additional name-value pairs given in the rule 
  41.      */  
  42.     public function validatePassword($attribute, $params)  
  43.     {  
  44.         if (!$this->hasErrors()) {  
  45.             $user = $this->getUser();  
  46.   
  47.             if (!$user || !$user->validatePassword($this->password)) {  
  48.                 $this->addError($attribute, 'Incorrect username or password.');  
  49.             }  
  50.         }  
  51.     }  
  52.   
  53.     /** 
  54.      * Logs in a user using the provided username and password. 
  55.      * @return boolean whether the user is logged in successfully 
  56.      */  
  57.     public function login()  
  58.     {  
  59.         if ($this->validate()) {  
  60.             if($this->rememberMe)  
  61.             {  
  62.                 $this->_user->generateAuthKey();//③  
  63.             }  
  64.             return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0);  
  65.         }  
  66.         return false;  
  67.     }  
  68.   
  69.     /** 
  70.      * Finds user by [[username]] 
  71.      * 
  72.      * @return User|null 
  73.      */  
  74.     public function getUser()  
  75.     {  
  76.         if ($this->_user === false) {  
  77.             $this->_user = User::findByUsername($this->username); //②  
  78.         }  
  79.   
  80.         return $this->_user;  
  81.     }  
  82. }  

該Model是根據basic模板自帶的LoginForm修改而成,代碼中大多有注釋,這里關注以下代碼:

①號代 碼處是rules規則,rules規則定義了填充過來的數據的規則,驗證所填的數據是否為空,是否符合格式之類的,其中有一欄是password,對應的 規則是validatePassword,會自動調用當前類的validatePassword()方法,注意與下文的User類對應的方法區分。

②號代碼,調用了User類里面的findByUsername方法,這個User類下面會寫到,主要是為了返回一個AR類實例,與當前LoginForm的數據進行比較。

③號代碼,這里暫時不提,等講到cookie登陸的時候再提。


2、User.php

(1)ActiveRecord 類

在 完成LoginForm后,我們還缺少一些東西,從用戶接受到數據了,那么還需要從數據庫取出相應的數據來進行比較,所以我們接下來需要完成的是一個從數 據庫獲取的數據的類——AR類,全稱是ActiveRecord,活動記錄類,方便用於查找數據,只要類名和數據表的表名相同,那么它就能從這個數據表中 獲取數據,比如說這樣:

 

  1. <?php  
  2. namespace app\modules\backend\models;  
  3. use yii\db\ActiveRecord;  
  4.   
  5. class User extends ActiveRecord{       } ?>  

此外,還能自己添加返回的表名,只要在這個類中重寫以下方法:

 

  1. public static function tableName(){  
  2.         return 'user';  
  3.     }  


(2)IdentityInterface 接口

一 般來說,從數據庫查找數據,只需要繼承AR類即可,但是,我們這個是用戶登錄模型,核心是驗證,所以自然需要實現核心的驗證功能,就像LoginForm 模型提到的validatePassword一樣,實際的驗證邏輯是在當前的User模型完成的。一般來說,實現IdentityInterface接 口,需要實現以下方法:

 

  1. public static function findIdentity($id);  //①  
  2.   
  3. public static function findIdentityByAccessToken($token, $type = null);   //②  
  4.   
  5. public function getId();    //③  
  6.   
  7. public function getAuthKey();   //④  
  8.   
  9. public function validateAuthKey($authKey);    //⑤  

①findIdentity:是根據id查找數據表對應的數據

②findIdentityByAccessToken 是根據AccessToken(上文提到的)查找對應的數據,而AccessToken我們在數據表也有這個字段,那么它到底有什么用呢?其實 AccessToken在我們當前的用戶登陸模型中用處並不大,它是專門用於Resetful登陸驗證用到的,具體可自行百度,這里不展開說明。

③getId:返回當前AR類所對應的id

④getAuthKey:返回當前AR類所對應的auth_key

⑤validateAuthKey:這個方法比較重要,是我們后面要講到的cookie登陸驗證的核心所在。

好了,既然知道了這五個方法的用處,那么我們在我們的User.php實現接口,然后重寫以上方法,完整的User.php的代碼如下:

 

  1. <?php  
  2. namespace app\modules\backend\models;  
  3. use yii\db\ActiveRecord;  
  4.   
  5. class User extends ActiveRecord implements \yii\web\IdentityInterface  
  6. {  
  7.   
  8.     public static function tableName(){  
  9.         return 'user';  
  10.     }  
  11.   
  12.     public static function findIdentity($id){  
  13.         return static::findOne($id);  
  14.     }  
  15.   
  16.     public static function findIdentityByAccessToken($token,$type=null){  
  17.         return static::findOne(['accessToken'=>$token]);  
  18.     }  
  19.   
  20.     public static function findByUsername($username){     //①  
  21.         return static::findOne(['username'=>$username]);   
  22.     }  
  23.   
  24.     public function getId(){  
  25.         return $this->id;  
  26.     }  
  27.   
  28.     public function getAuthkey(){  
  29.         return $this->auth_key;  
  30.     }  
  31.   
  32.     public function validateAuthKey($authKey){  
  33.         return $this->auth_key === $authKey;  
  34.     }  
  35.   
  36.     public function validatePassword($password){          //②  
  37.         return $this->password === md5($password);  
  38.     }  
  39.   
  40.    <span style="white-space:pre"> </span> /** 
  41.     <span style="white-space:pre">    </span> * Generates "remember me" authentication key 
  42.     <span style="white-space:pre">    </span> */  
  43.         public function generateAuthKey()                    //③  
  44.         {  
  45.        <span style="white-space:pre">     </span>$this->auth_key = \Yii::$app->security->generateRandomString();  
  46.        <span style="white-space:pre">     </span>$this->save();  
  47.         }  
  48.   
  49. }  
  50. ?>  

這里分析其中的三個方法:

①findByUsername():在LoginForm的代碼中,引用了這個方法,目的是根據用戶提交的username返回一個在數據表與username相同的數據項,即AR實例。

②validatePassword():這里對用戶提交的密碼以及當前AR類的密碼進行比較。

③generateAuthKey():生成隨機的auth_key,用於cookie登陸。

 

到此,我們完成了Model的編寫,一共寫了兩個Model類:LoginForm和User,一個用於接收用戶提交的數據,一個用於獲取數據庫的數據,接下來我們編寫Controller.


三、控制器(Controller)

控制器,主要是用於數據的提交,把用戶提交的數據填充到相應的模型(Model)中,然后根據模型返回的信息進一步渲染視圖(View),或者執行其他邏輯。

     這里,把控制器命名為LoginController.php,以下是完整的實現代碼:

 

  1. <?php  
  2.   
  3. namespace app\controllers;  
  4.   
  5. use Yii;  
  6. use yii\filters\AccessControl;  
  7. use yii\web\Controller;  
  8. use yii\filters\VerbFilter;  
  9. use app\models\LoginForm;  
  10. use app\models\ContactForm;  
  11.   
  12. class SiteController extends Controller  
  13. {  
  14.     public function actionIndex()  
  15.     {  
  16.         return $this->render('index');  
  17.     }  
  18.   
  19.     public function actionLogin()  
  20.     {  
  21.         if (!\Yii::$app->user->isGuest) {     //①  
  22.             return $this->goHome();  
  23.         }  
  24.   
  25.         $model = new LoginForm();             //②  
  26.         if ($model->load(Yii::$app->request->post()) && $model->login()) {      //③  
  27.             return $this->goBack();          //④  
  28.         }  
  29.         return $this->render('login', [      //⑤  
  30.             'model' => $model,  
  31.         ]);  
  32.     }  
  33.   
  34.     public function actionLogout()  
  35.     {  
  36.         Yii::$app->user->logout();  
  37.   
  38.         return $this->goHome();  
  39.     }  
  40. }  

關注其中的actionLogin()方法:

①首先從\Yii::$app->user->isGuest中判斷,當前是否是游客模式,即未登陸狀態,如果用戶已經登陸,會在user類中儲存當前登陸用戶的信息。

②如果當前是游客,會先實例化一個LoginForm模型

③這行 代碼是整個login方法的核心所在,首先:$model->load(Yii::$app->request->post())把 post過來的數據填充進$model,即LoginForm模型,如果返回true,則填充成功。接着:$model->login():執行 LoginForm類里面的login()方法,可以從login()方法里面看到,將會執行一系列的驗證。

關於Yii框架到底是怎樣進行用戶登陸的,底層是怎樣實現的,我們在下一篇文章詳談,這里先說明實現方法。


四、視圖(View)

在實現了model和controller,接下來是視圖部分,由於用戶需要輸入數據,所以我們要提供一個表單,在Yii2中,提供了ActiveForm快速生成表單,代碼如下:

 

  1. <?php  
  2.   
  3. /* @var $this yii\web\View */  
  4. /* @var $form yii\bootstrap\ActiveForm */  
  5. /* @var $model app\models\LoginForm */  
  6.   
  7. use yii\helpers\Html;  
  8. use yii\bootstrap\ActiveForm;  
  9.   
  10. $this->title = 'Login';  
  11. $this->params['breadcrumbs'][] = $this->title;  
  12. ?>  
  13. <div class="site-login">  
  14.     <h1><?= Html::encode($this->title) ?></h1>  
  15.   
  16.     <p>Please fill out the following fields to login:</p>  
  17.   
  18.     <?php $form = ActiveForm::begin([  
  19.         'id' => 'login-form',  
  20.         'options' => ['class' => 'form-horizontal'],  
  21.         'fieldConfig' => [  
  22.             'template' => "{label}\n<div class=\"col-lg-3\">{input}</div>\n<div class=\"col-lg-8\">{error}</div>",  
  23.             'labelOptions' => ['class' => 'col-lg-1 control-label'],  
  24.         ],  
  25.     ]); ?>  
  26.   
  27.         <?= $form->field($model, 'username')->textInput(['autofocus' => true]) ?>  
  28.   
  29.         <?= $form->field($model, 'password')->passwordInput() ?>  
  30.   
  31.         <?= $form->field($model, 'rememberMe')->checkbox([  
  32.             'template' => "<div class=\"col-lg-offset-1 col-lg-3\">{input} {label}</div>\n<div class=\"col-lg-8\">{error}</div>",  
  33.         ]) ?>  
  34.   
  35.         <div class="form-group">  
  36.             <div class="col-lg-offset-1 col-lg-11">  
  37.                 <?= Html::submitButton('Login', ['class' => 'btn btn-primary', 'name' => 'login-button']) ?>  
  38.             </div>  
  39.         </div>  
  40.   
  41.     <?php ActiveForm::end(); ?>  
  42.   
  43.     <div class="col-lg-offset-1" style="color:#999;">  
  44.         You may login with <strong>admin/admin</strong> or <strong>demo/demo</strong>.<br>  
  45.         To modify the username/password, please check out the code <code>app\models\User::$users</code>.  
  46.     </div>  
  47. </div>  

$form=ActiveForm::begin() :創建一個Form表單

$form=field()->textInput()   :創建一個文本輸入框

$form=field()->checkbox() :創建一個checkbox

Html::submitButton():          創建一個登陸按鈕

ActiveForm::end()    :   結束表單


以上,就是創建一個用戶登陸模塊的全流程,這里對用戶登陸的細節和怎樣實現cookie自動登陸只是一筆帶過,更詳細的源碼分析請看下一篇博文,謝謝。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM