Yii2在MySQL中从表登录的分步指南 [英] Yii2 step-by-step guide on login from table in MySQL

查看:134
本文介绍了Yii2在MySQL中从表登录的分步指南的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始在Yii2中迈出第一步.到目前为止,我已经能够编写应用程序并将数据库中的表连接到该表,就像我在Yii1中学到的那样.

I'm begining to make the first steps in 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.

表为contacts,并且在我的create视图中的表单将数据毫无问题地发送到数据库.

The table is contacts and the form in my create view sends the data to the database with no problems.

问题在于,我只能使用Yii2内置的静态用户模型中的Admin/Admin或demo/demo登录.

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.

在Yii1.xx中,我设法使用COMPONENTS/useridentity验证从数据库中的表登录,就像这样(我使用了名为utilizador的表,具有字段idutilizadorpassword):

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):

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,而且我不知道从哪里开始,什么才是使它起作用的适当代码,以取代现成的静态用户模型.

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 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-user,阅读了PDF指南,但不了解如何从控制器中的vendor文件夹调用路由.尝试了几次,但都失败了.

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. Made several tries but all failed.

有人可以教我如何从Yii2的数据库中验证登录名,而不使用扩展名吗?

Can someone teach me how to validate login from database in Yii2, preferentially without using an extension?

修改

我在Stack Overflow中阅读了本教程 Yii Framework 2.0使用用户数据库登录

并且还研究了Yii2用户扩展名中的PDF ,但不知道如何处理下一部分和下一部分pdf.它谈到了路线,但我不知道如何与之合作:

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. It speaks about routes, but i don't know how to work with them:

2.3.1显示用户 路由/user/admin/index显示已注册用户的列表.您将能够看到很多有用的信息,例如注册时间和IP地址,确认和阻止状态等.

2.3.1 Show users Route /user/admin/index shows a list of registered users. You will be able to see a lot of useful information such as registration time and ip address, confirmation and block status, etc.

我也阅读过此内容: http://www.yiiframework.com/doc-2.0/yii- web-user.html 但我认为它没有解决问题的步骤.

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.

编辑2

我试图在Yii基本模板中实现用户模型和LoginForm模型,以验证用户登录.创建一个数据库并连接到该数据库.作为表用户的数据库,并使用值填充字段用户名,密码,authKey,acessToken.从ActiveRecord扩展了用户模型并实现了\ yii \ web \ IdentityInterface,以使内置的Yii2函数发挥作用.还编写了方法公共静态函数tableName(){return'user'; }

I tried to implement the User Model and LoginForm Model in Yii basic template to validate user logins. Created a database and coneected to it. The database as a table user and fields username, password, authKey, acessToken populated with values. Extended the User Model from ActiveRecord and implemented \yii\web\IdentityInterface in order to make the in-built Yii2 functions do their job. Also wrrited the method public static function tableName() { return 'user'; }

每次尝试登录时,都会抛出->用户名或密码不正确,原因是LoginForm模型中的validatepassword().

Every time i try to login it throws -> username or password incorrect, from the validatepassword() in LoginForm Model.

这是我的代码: LoginForm模型:

Here is my code: 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高级应用程序默认带有来自数据库的登录部分的有效示例(我看到基本的使用静态用户名和密码).您无需安装任何额外的东西,只需看一下代码即可.安装高级应用程序并查看前端.

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). You do not have to install anything extra, just look at the code. Install the advanced app and take a look at the frontend.

简而言之,SiteController使用LoginModel进行验证,然后使用LoginModel的login()将User模型登录到User组件.

In short SiteController uses LoginModel for validation then uses the login() of the LoginModel to login the User model to the User component.

如果您不想使用用户模型,只需创建自己的模型并使用该模型即可.您不想使用默认的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.

修改: 配合,删除下面的变量的公共声明.

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;

您要告诉Yii忽略数据库中的内容.

You are telling Yii to ignore what is in the database.

这篇关于Yii2在MySQL中从表登录的分步指南的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆