簡體   English   中英

關於從MySQL中的表登錄的Yii2循序漸進指南

[英]Yii2 step-by-step guide on login from table in MySQL

我開始在Yii2中邁出第一步。 到目前為止,我能夠編寫一個應用程序並將數據庫中的表連接到它,就像我在Yii1中學到的那樣。

該表是contacts ,我的創建視圖中的表單將數據發送到數據庫沒有任何問題。

問題是我只能使用內置在Yii2中的靜態用戶模型中的Admin / Admin或demo / demo登錄。

在Yii1.xx中,我設法使用COMPONENTS / useridentity從數據庫中的表中驗證登錄,就像這樣(我使用了一個名為utilizador的表,其中包含字段idutilizadorpassword ):

class UserIdentity extends CUserIdentity
{

    public function authenticate() {
       $conexao=Yii::app()->db;
       $consulta="select utilizador,password from utilizador ";
       $consulta.="where utilizador='".$this->username."' and ";
       $consulta.="password='".$this->password."'";

       $resultado=$conexao->createCommand($consulta)->query();

       $resultado->bindColumn(1,$this->username);
       $resultado->bindColumn(2,$this->password);

       while($resultado->read()!==false){
        $this->errorCode=self::ERROR_NONE;
        return !$this->errorCode;
       }
   }

}

有了Yii2,我已經閱讀了很多教程,包括Stack Overflow中的一個,但是沒有一個能讓我了解從MySQL數據庫登錄用戶名和密碼的過程。 Yii2沒有components / useridentity.php,我不知道從哪里開始,什么是正確的代碼,使它能夠覆蓋開箱即用的靜態用戶模型。

我也嘗試過擴展Yii2用戶,閱讀PDF指南,但不知道如何從我的控制器中的供應商文件夾中調用路由。 做了幾次嘗試,但都失敗了。

有人可以教我如何在Yii2中驗證從數據庫登錄,優先不使用擴展嗎?

編輯

我在Stack Overflow Yii Framework 2.0使用用戶數據庫登錄時 閱讀了本教程

並且還研究了來自Yii2用戶擴展的PDF ,但不知道如何處理以下部分和下一部分pdf。 它講的是路線,但我不知道如何使用它們:

2.3.1顯示用戶Route / user / admin / index顯示注冊用戶列表。 您將能夠看到許多有用的信息,例如注冊時間和IP地址,確認和阻止狀態等。

我也讀過這個: http //www.yiiframework.com/doc-2.0/yii-web-user.html但我不認為它有解決問題的步驟。

編輯2

我嘗試在Yii基本模板中實現User Model和LoginForm Model來驗證用戶登錄。 創建了一個數據庫並與之相關聯。 數據庫作為表用戶和字段用戶名,密碼,authKey,acessToken填充值。 從ActiveRecord擴展用戶模型並實現\\ yii \\ web \\ IdentityInterface,以使內置的Yii2功能完成其工作。 還寫了方法public static function tableName(){ return'user '; }

每次我嘗試登錄時,從LoginForm模型中的validatepassword()拋出 - >用戶名或密碼不正確。

這是我的代碼:LoginForm Model:

namespace app\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()
{
    return [
        // username and password are both required
        [['username', 'password'], 'required'],
        // 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()) {
        return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0);
    } else {
        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;
}

}

...這是我的User.php模型

<?php

namespace app\models;

use yii\db\ActiveRecord;

class User extends ActiveRecord implements \yii\web\IdentityInterface
{
public $id;
public $username;
public $password;
public $authKey;
public $accessToken;

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

   /**
 * @inheritdoc
 */
public static function findIdentity($id) {
    $user = self::find()
            ->where([
                "id" => $id
            ])
            ->one();
    if (!count($user)) {
        return null;
    }
    return new static($user);
}

/**
 * @inheritdoc
 */
public static function findIdentityByAccessToken($token, $userType = null) {

    $user = self::find()
            ->where(["accessToken" => $token])
            ->one();
    if (!count($user)) {
        return null;
    }
    return new static($user);
}

/**
 * Finds user by username
 *
 * @param  string      $username
 * @return static|null
 */
public static function findByUsername($username) {
    $user = self::find()
            ->where([
                "username" => $username
            ])
            ->one();
    if (!count($user)) {
        return null;
    }
    return new static($user);
}

/**
 * @inheritdoc
 */
public function getId() {
    return $this->id;
}

/**
 * @inheritdoc
 */
public function getAuthKey() {
    return $this->authKey;
}

/**
 * @inheritdoc
 */
public function validateAuthKey($authKey) {
    return $this->authKey === $authKey;
}

/**
 * Validates password
 *
 * @param  string  $password password to validate
 * @return boolean if password provided is valid for current user
 */
public function validatePassword($password) {
    return $this->password === $password;
}

}

有任何想法嗎 ?? - >謝謝......

我不知道我還應該做什么,也許它在驗證密碼或找到用戶名方面存在問題,在Yii2調試中它顯示正確連接到mysql數據庫。

不要觸及siteController actionLogin(),因為它等於高級模板,我認為最好保持這種方式。

編輯3 - > 4小時搞亂模型代碼,在我閱讀的每個解決方案中加入實踐,它仍然會拋出“用戶名或密碼不正確”。 從:

public function validatePassword($attribute, $params)
{
    if (!$this->hasErrors()) {
        $user = $this->getUser();

        if (!$user || !$user->validatePassword($this->password)) {
            $this->addError($attribute, 'Incorrect username or password.');
        }
    }
}

我不想放棄,但我正在考慮回到舊的Yii1.xx. 在那里,我可以輕松地查詢數據庫,並使一個良好的登錄系統工作。

Yii2高級應用程序默認帶有來自數據庫的登錄部分的工作示例(我看到基本部分使用靜態用戶名和密碼)。 您無需安裝任何額外的東西,只需查看代碼即可。 安裝高級應用程序並查看前端。

簡而言之,SiteController使用LoginModel進行驗證,然后使用LoginModel的login()將User模型登錄到User組件。

如果您不想使用用戶模型,只需創建自己的模型並使用該模型。 您不想使用默認的用戶組件,只需創建自己的組件。 這很容易做到。

編輯:交配,刪除變量的公共聲明。

class User extends ActiveRecord implements \yii\web\IdentityInterface
{
public $id;
public $username;
public $password;
public $authKey;
public $accessToken;

你告訴Yii忽略數據庫中的內容。

創建自己的模型,然后使用它。 我將在下面發布代碼。

1)首先根據自己的要求創建數據庫表。

 CREATE TABLE `q_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `email` varchar(255) NOT NULL,
  `auth_key` varchar(32) NOT NULL,
  `password_hash` varchar(20) NOT NULL,
  `access_token` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; 
  • 現在轉到Model生成器並使用q_user表創建Model

  • 它將生成一個QUser模型。 在這個模型中你將不得不
    實現IdentityInterface

    class QUser extends \\ yii \\ db \\ ActiveRecord實現\\ yii \\ web \\ IdentityInterface

現在實現所有方法。 如果使用Netbeans命中alt + enter。

public function getAuthKey() {
        return $this->auth_key;
    }

    public function getId() {
        return $this->id;
    }

    public function validateAuthKey($authKey) {
       return $this->auth_key = $authkey;
    }

    public static function findIdentity($id) {

        return self::findOne($id);

    }

    public static function findIdentityByAccessToken($token, $type = null) {

        return $this->access_token;
    }

    public static function findByUsername($email){
        return self::findOne(['email'=>$email]);
    }

    public function validatePassword($password){
        return $this->password_hash === $password;
    }
  • 現在,在Login窗體中,您將必須定義Quser模型,以便它返回用戶

    class LoginForm擴展Model {public $ username; public $ password; public $ email; public $ rememberMe = true;

     private $_user = false; /** * @return array the validation rules. */ public function rules() { return [ // username and password are both required [['email', 'password'], 'required'], // rememberMe must be a boolean value ['rememberMe', 'boolean'], // password is validated by validatePassword() ['password', 'validatePassword'], ['password','match','pattern'=>'$\\S*(?=\\S*[az])(?=\\S*[AZ])(?=\\S*[\\d])\\S*$','message'=>'Password must have atleast 1 uppercase and 1 number '], [['password'],'string','min'=>6], //email validation ['email','email'] ]; } /** * 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()) { 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 = QUser::findByUsername($this->email); } return $this->_user; } 

    }

就是這樣可以解決你的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM