溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

yii如何做登錄

發(fā)布時間:2020-12-22 11:46:48 來源:億速云 閱讀:159 作者:小新 欄目:編程語言

這篇文章給大家分享的是有關(guān)yii如何做登錄的內(nèi)容。小編覺得挺實用的,因此分享給大家做個參考。一起跟隨小編過來看看吧。

yii做登錄的方法示例:

1、LoginForm.php

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

<?php
 
namespace app\modules\backend\models;
 
use Yii;
use yii\base\Model;
 
/**
 * LoginForm is the model behind the login form.
 */
class LoginForm extends Model
{
    public $username;
    public $password;
    public $rememberMe = true;
 
    private $_user = false;
 
 
    /**
     * @return array the validation rules.
     */
    public function rules()<span style="white-space:pre">		</span>//①
    {
        return [
            // username and password are both required
            [['username', 'password'], 'required','message'=>""],
            // rememberMe must be a boolean value
            ['rememberMe', 'boolean'],
            // password is validated by validatePassword()
            ['password', 'validatePassword'],
        ];
    }
 
    /**
     * Validates the password.
     * This method serves as the inline validation for password.
     *
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validatePassword($attribute, $params)
    {
        if (!$this->hasErrors()) {
            $user = $this->getUser();
 
            if (!$user || !$user->validatePassword($this->password)) {
                $this->addError($attribute, 'Incorrect username or password.');
            }
        }
    }
 
    /**
     * Logs in a user using the provided username and password.
     * @return boolean whether the user is logged in successfully
     */
    public function login()
    {
        if ($this->validate()) {
            if($this->rememberMe)
            {
                $this->_user->generateAuthKey();//③
            }
            return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0);
        }
        return false;
    }
 
    /**
     * Finds user by [[username]]
     *
     * @return User|null
     */
    public function getUser()
    {
        if ($this->_user === false) {
            $this->_user = User::findByUsername($this->username); //②
        }
 
        return $this->_user;
    }
}

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

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

②號代碼,調(diào)用了User類里面的findByUsername方法,這個User類下面會寫到,主要是為了返回一個AR類實例,與當(dāng)前LoginForm的數(shù)據(jù)進(jìn)行比較。

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

2、User.php

(1)ActiveRecord 類

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

<?php
namespace app\modules\backend\models;
use yii\db\ActiveRecord;
 
class User extends ActiveRecord{       } ?>

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

public static function tableName(){
		return 'user';
	}

(2)IdentityInterface 接口

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

    public static function findIdentity($id);  //①
 
    public static function findIdentityByAccessToken($token, $type = null);   //②
 
    public function getId();    //③
 
    public function getAuthKey();   //④
 
    public function validateAuthKey($authKey);    //⑤

①findIdentity:是根據(jù)id查找數(shù)據(jù)表對應(yīng)的數(shù)據(jù)

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

③getId:返回當(dāng)前AR類所對應(yīng)的id

④getAuthKey:返回當(dāng)前AR類所對應(yīng)的auth_key

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

在我們的User.php實現(xiàn)接口,然后重寫以上方法,完整的User.php的代碼如下:

<?php
namespace app\modules\backend\models;
use yii\db\ActiveRecord;
 
class User extends ActiveRecord implements \yii\web\IdentityInterface
{
 
	public static function tableName(){
		return 'user';
	}
 
	public static function findIdentity($id){
		return static::findOne($id);
	}
 
	public static function findIdentityByAccessToken($token,$type=null){
		return static::findOne(['accessToken'=>$token]);
	}
 
	public static function findByUsername($username){     //①
		return static::findOne(['username'=>$username]); 
	}
 
	public function getId(){
		return $this->id;
	}
 
	public function getAuthkey(){
		return $this->auth_key;
	}
 
	public function validateAuthKey($authKey){
		return $this->auth_key === $authKey;
	}
 
	public function validatePassword($password){          //②
		return $this->password === md5($password);
	}
 
   <span style="white-space:pre">	</span> /**
    <span style="white-space:pre">	</span> * Generates "remember me" authentication key
    <span style="white-space:pre">	</span> */
        public function generateAuthKey()                    //③
        {
       <span style="white-space:pre">		</span>$this->auth_key = \Yii::$app->security->generateRandomString();
       <span style="white-space:pre">		</span>$this->save();
        }
 
}
?>

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

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

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

一共寫了兩個Model類:LoginForm和User,一個用于接收用戶提交的數(shù)據(jù),一個用于獲取數(shù)據(jù)庫的數(shù)據(jù)。

控制器(Controller)

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

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

<?php
 
namespace app\controllers;
 
use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;
use app\models\LoginForm;
use app\models\ContactForm;
 
class SiteController extends Controller
{
    public function actionIndex()
    {
        return $this->render('index');
    }
 
    public function actionLogin()
    {
        if (!\Yii::$app->user->isGuest) {     //①
            return $this->goHome();
        }
 
        $model = new LoginForm();             //②
        if ($model->load(Yii::$app->request->post()) && $model->login()) {      //③
            return $this->goBack();          //④
        }
        return $this->render('login', [      //⑤
            'model' => $model,
        ]);
    }
 
    public function actionLogout()
    {
        Yii::$app->user->logout();
 
        return $this->goHome();
    }
}

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

②如果當(dāng)前是游客,會先實例化一個LoginForm模型

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

視圖(View)

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

<?php
 
/* @var $this yii\web\View */
/* @var $form yii\bootstrap\ActiveForm */
/* @var $model app\models\LoginForm */
 
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
 
$this->title = 'Login';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="site-login">
    <h2><?= Html::encode($this->title) ?></h2>
    <p>Please fill out the following fields to login:</p>
    <?php $form = ActiveForm::begin([
        'id' => 'login-form',
        'options' => ['class' => 'form-horizontal'],
        'fieldConfig' => [
            'template' => "{label}\n<div class=\"col-lg-3\">{input}</div>\n<div class=\"col-lg-8\">{error}</div>",
            'labelOptions' => ['class' => 'col-lg-1 control-label'],
        ],
    ]); ?>
        <?= $form->field($model, 'username')->textInput(['autofocus' => true]) ?>
        <?= $form->field($model, 'password')->passwordInput() ?>
        <?= $form->field($model, 'rememberMe')->checkbox([
            'template' => "<div class=\"col-lg-offset-1 col-lg-3\">{input} {label}</div>\n<div class=\"col-lg-8\">{error}</div>",
        ]) ?>
        <div class="form-group">
            <div class="col-lg-offset-1 col-lg-11">
                <?= Html::submitButton('Login', ['class' => 'btn btn-primary', 'name' => 'login-button']) ?>
            </div>
        </div>
    <?php ActiveForm::end(); ?>
    <div class="col-lg-offset-1" style="color:#999;">
        You may login with <strong>admin/admin</strong> or <strong>demo/demo</strong>.<br>
        To modify the username/password, please check out the code <code>app\models\User::$users</code>.
    </div>
</div>

感謝各位的閱讀!關(guān)于yii如何做登錄就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,讓大家可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

yii
AI