简体   繁体   English

关于从MySQL中的表登录的Yii2循序渐进指南

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

I'm begining to make the first steps in Yii2. 我开始在Yii2中迈出第一步。 So far, I was able to write an application and connect a table in a database to it, just like I learned to do in Yii1. 到目前为止,我能够编写一个应用程序并将数据库中的表连接到它,就像我在Yii1中学到的那样。

The table is contacts and the form in my create view sends the data to the database with no problems. 该表是contacts ,我的创建视图中的表单将数据发送到数据库没有任何问题。

The problem is that I only can login using Admin/Admin or demo/demo in the static user model that comes built-in in Yii2. 问题是我只能使用内置在Yii2中的静态用户模型中的Admin / Admin或demo / demo登录。

In Yii1.xx i manage to validate login from a table in database using COMPONENTS/useridentity, just like this (I used a table named utilizador , with fields id , utilizador and password ): 在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;
       }
   }

}

With Yii2 I have read a lot of tutorials, including one in Stack Overflow but none of them enlighten me on the procedure to login users with username and password from a MySQL database. 有了Yii2,我已经阅读了很多教程,包括Stack Overflow中的一个,但是没有一个能让我了解从MySQL数据库登录用户名和密码的过程。 Yii2 don't have components/useridentity.php and I don't know where to start and what is the proper code to make it work overriding the static user model that comes out of the box. Yii2没有components / useridentity.php,我不知道从哪里开始,什么是正确的代码,使它能够覆盖开箱即用的静态用户模型。

I also have tried an extension Yii2-user, read the PDF guide but didn't understand how to call the route's from the vendor folder in my controllers. 我也尝试过扩展Yii2用户,阅读PDF指南,但不知道如何从我的控制器中的供应商文件夹中调用路由。 Made several tries but all failed. 做了几次尝试,但都失败了。

Can someone teach me how to validate login from database in Yii2, preferentially without using an extension? 有人可以教我如何在Yii2中验证从数据库登录,优先不使用扩展吗?

Edit 编辑

I read this tutorial in Stack Overflow Yii Framework 2.0 Login With User Database 我在Stack Overflow Yii Framework 2.0使用用户数据库登录时 阅读了本教程

And also studied the PDF from Yii2-user extension , but don't know what to do with following part and next ones of the pdf. 并且还研究了来自Yii2用户扩展的PDF ,但不知道如何处理以下部分和下一部分pdf。 It speaks about routes, but i don't know how to work with them: 它讲的是路线,但我不知道如何使用它们:

2.3.1 Show users Route /user/admin/index shows a list of registered users. 2.3.1显示用户Route / user / admin / index显示注册用户列表。 You will be able to see a lot of useful information such as registration time and ip address, confirmation and block status, etc. 您将能够看到许多有用的信息,例如注册时间和IP地址,确认和阻止状态等。

I have also read this: http://www.yiiframework.com/doc-2.0/yii-web-user.html but I don't think it has the steps to resolve my problem. 我也读过这个: http //www.yiiframework.com/doc-2.0/yii-web-user.html但我不认为它有解决问题的步骤。

EDIT 2 编辑2

I tried to implement the User Model and LoginForm Model in Yii basic template to validate user logins. 我尝试在Yii基本模板中实现User Model和LoginForm Model来验证用户登录。 Created a database and coneected to it. 创建了一个数据库并与之相关联。 The database as a table user and fields username, password, authKey, acessToken populated with values. 数据库作为表用户和字段用户名,密码,authKey,acessToken填充值。 Extended the User Model from ActiveRecord and implemented \\yii\\web\\IdentityInterface in order to make the in-built Yii2 functions do their job. 从ActiveRecord扩展用户模型并实现\\ yii \\ web \\ IdentityInterface,以使内置的Yii2功能完成其工作。 Also wrrited the method public static function tableName() { return 'user'; 还写了方法public static function tableName(){ return'user '; } }

Every time i try to login it throws -> username or password incorrect, from the validatepassword() in LoginForm Model. 每次我尝试登录时,从LoginForm模型中的validatepassword()抛出 - >用户名或密码不正确。

Here is my code: LoginForm Model: 这是我的代码: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;
}

} }

... and here is my User.php Model ...这是我的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;
}

}

Any ideas ?? 有任何想法吗 ?? -> Thanks... - >谢谢......

I don't know what else should i do, perhaps it has a problem in validating the password or find the username, in Yii2 debug it shows that is proper connected to the mysql database. 我不知道我还应该做什么,也许它在验证密码或找到用户名方面存在问题,在Yii2调试中它显示正确连接到mysql数据库。

Don't touched in the siteController actionLogin() because it is equal to the advanced template and i think it is better to stay that way. 不要触及siteController actionLogin(),因为它等于高级模板,我认为最好保持这种方式。

EDIT 3 -> 4 HOURS messing with the models code, putting in pratice every solution i read and it still throws "Incorrect username or password." 编辑3 - > 4小时搞乱模型代码,在我阅读的每个解决方案中加入实践,它仍然会抛出“用户名或密码不正确”。 from: 从:

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

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

I don't want to give up, but i'm considering go back to the old Yii1.xx. 我不想放弃,但我正在考虑回到旧的Yii1.xx. There i could easily query the database and make a good login system working. 在那里,我可以轻松地查询数据库,并使一个良好的登录系统工作。

Yii2 advanced app comes by default with a working example of the login part from the DB (I see the basic ones uses a static username and password). Yii2高级应用程序默认带有来自数据库的登录部分的工作示例(我看到基本部分使用静态用户名和密码)。 You do not have to install anything extra, just look at the code. 您无需安装任何额外的东西,只需查看代码即可。 Install the advanced app and take a look at the frontend. 安装高级应用程序并查看前端。

In short SiteController uses LoginModel for validation then uses the login() of the LoginModel to login the User model to the User component. 简而言之,SiteController使用LoginModel进行验证,然后使用LoginModel的login()将User模型登录到User组件。

If you do not want to use the User model, just create your own model and use that one. 如果您不想使用用户模型,只需创建自己的模型并使用该模型。 You do not want to use the default User component, just create your own. 您不想使用默认的用户组件,只需创建自己的组件。 It is quite easy to do. 这很容易做到。

Edit: mate, remove the public declarations of variables bellow. 编辑:交配,删除变量的公共声明。

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

You are telling Yii to ignore what is in the database. 你告诉Yii忽略数据库中的内容。

Create your own model and then use that. 创建自己的模型,然后使用它。 I will post the code below. 我将在下面发布代码。

1) First create a database table with your own requirements. 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; 
  • Now go to the Model generator and create a Model using the q_user table 现在转到Model生成器并使用q_user表创建Model

  • It will generate a QUser model. 它将生成一个QUser模型。 In this model you will have to 在这个模型中你将不得不
    implement the IdentityInterface 实现IdentityInterface

    class QUser extends \\yii\\db\\ActiveRecord implements \\yii\\web\\IdentityInterface class QUser extends \\ yii \\ db \\ ActiveRecord实现\\ yii \\ web \\ IdentityInterface

Now implement all the methods. 现在实现所有方法。 If using Netbeans hit alt+ enter. 如果使用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;
    }
  • Now in Login form you will have to define Quser model so it will return back the user 现在,在Login窗体中,您将必须定义Quser模型,以便它返回用户

    class LoginForm extends Model { public $username; class LoginForm扩展Model {public $ username; public $password; public $ password; public $email; public $ email; public $rememberMe = true; 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; } 

    } }

That's it this will solve your problem. 就是这样可以解决你的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM