database - 将 Yii2 登录表单连接到数据库

标签 database authentication yii2

我刚刚安装了 Yii2 Basic 并想将预先存在的登录表单映射到数据库。我怎样才能做到这一点?我已经准备好数据库并更改了数据库连接设置。我需要在模型中做哪些更改?这是我退出的登录模型:

<?php

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);
        }
        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;
    }
}

这是我的用户模型:

<?php

namespace app\models;

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

    private static $users = [
        '100' => [
            'id' => '100',
            'username' => 'admin',
            'password' => 'admin',
            'authKey' => 'test100key',
            'accessToken' => '100-token',
        ],
        '101' => [
            'id' => '101',
            'username' => 'demo',
            'password' => 'demo',
            'authKey' => 'test101key',
            'accessToken' => '101-token',
        ],
    ];

    /**
     * @inheritdoc
     */
    public static function findIdentity($id)
    {
        return isset(self::$users[$id]) ? new static(self::$users[$id]) : null;
    }

    /**
     * @inheritdoc
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        foreach (self::$users as $user) {
            if ($user['accessToken'] === $token) {
                return new static($user);
            }
        }

        return null;
    }

    /**
     * Finds user by username
     *
     * @param  string      $username
     * @return static|null
     */
    public static function findByUsername($username)
    {
        foreach (self::$users as $user) {
            if (strcasecmp($user['username'], $username) === 0) {
                return new static($user);
            }
        }

        return null;
    }

    /**
     * @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;
    }
}

如何更改它以实现从数据库的登录连接?

最佳答案

需要在User.php中改模型(主要是findIdentityfindByUsernamevalidatePassword三个方法) .下面的链接肯定会帮助您完成此操作。 Link 1 , Link 2Link 3

<?php

namespace app\models;
use app\models\Users; // generated using Gii; user master table in db

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

    /**
     * @inheritdoc
     */
    public static function findIdentity($id)
    {
        $user = Users::findOne(['id'=>$id]);
        if(!$user)
        {
            return null;
        }
        else
        {
            $user_info = 
                [
                    'id' => $user->id,
                    'username' => $user->username,
                    'first_name' => $user->first_name,
                    'last_name' => $user->last_name,
                    'email' => $user->email,                                
                    'image'=>$user->image,                
                    // assign other attributes too if needed
                ];
            return new static($user_info);
        }
    }

    /**
     * Finds user by username
     *
     * @param  string      $username
     * @return static|null
     */
    public static function findByUsername($username)
    {
        $user = Users::findOne(['id'=>$id]);
        if(!$user)
        {
            return null;
        }
        else
        {
            $user_info = 
                [
                    'id' => $user->id,
                    'username' => $user->username,
                    'first_name' => $user->first_name,
                    'last_name' => $user->last_name,
                    'email' => $user->email,                                
                    'image'=>$user->image,                
                    // assign other attributes, too if needed
                ];
            return new static($user_info);
        }

        return null;
    }

    /**
     * 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; // apply any encryption algo here to $password, if you have used any
    }

    // ...
    // ... other functions here
}

关于database - 将 Yii2 登录表单连接到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35241666/

相关文章:

mysql - 将数据从表 A 插入表 B WHERE(条件)& SET Col.a = "xxx"

database - 这是将远程数据库复制到开发中最安全的方法吗?

mysql - 将 varchar() 限制为 a-z 范围

ubuntu - 更改主机名后,gedit(和其他 X 客户端)无法打开

json - postman - 错误 400 错误请求

php - Yii2:具有高级配置的通用 Assets

php - Yii2:使用一个字段搜索多列

MYSQL:带有异常(exception)条件的 LIKE

javascript - 如何在删除节点后使用 fancytree 小部件(Yii2)重新加载整个树

ruby-on-rails - 我应该在哪里使用 Devise + RSpec 进行经过身份验证的路由测试?