繁体   English   中英

Yii2使用数据库登录

[英]Yii2 Login with database

我在数据库中有一个名为“ member”的表,我打算在其中存储用户名,密码和用户的所有其他相关信息,我想使用这些用户名/密码登录,而不是使用yii2的默认User.php模型。 我已经尝试了将近一天,并修改了Member.php模型,但无法使其正常工作。 每次我使用数据库中的自定义用户名/密码时,都会显示用户名或密码不正确。 有人可以帮我吗? 提前致谢。 :)

仅供参考,成员表中没有此类字段,例如authKey或accessToken。 我已经尝试了所有相关的stackoverflow帖子,但有一些尝试。

Member.php模型

namespace app\models;
use Yii;
use yii\web\IdentityInterface;

class Member extends \yii\db\ActiveRecord implements IdentityInterface
{
    public static function tableName()
    {
        return 'member';
    }

    public function rules()
    {
        return [
            [['username', 'password', 'first_name', 'last_name', 'role'], 'required'],
            [['created_by_date', 'last_modified_by_date'], 'safe'],
            [['username', 'password', 'role', 'created_by_id', 'last_modified_by_id'], 'string', 'max' => 50],
            [['first_name', 'last_name', 'middle_name', 'phone', 'mobile'], 'string', 'max' => 100],
            [['email'], 'string', 'max' => 250],
            [['address_line1', 'address_line2', 'address_line3'], 'string', 'max' => 512]
        ];
    }

    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'username' => 'Username',
            'password' => 'Password',
            'first_name' => 'First Name',
            'last_name' => 'Last Name',
            'middle_name' => 'Middle Name',
            'email' => 'Email',
            'phone' => 'Phone',
            'mobile' => 'Mobile',
            'address_line1' => 'Address Line1',
            'address_line2' => 'Address Line2',
            'address_line3' => 'Address Line3',
            'role' => 'Role',
            'created_by_id' => 'Created By ID',
            'created_by_date' => 'Created By Date',
            'last_modified_by_id' => 'Last Modified By ID',
            'last_modified_by_date' => 'Last Modified By Date',
        ];
    }

    public static function find()
    {
        return new MemberQuery(get_called_class());
    }

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

    public static function findIdentityByAccessToken($token, $userType = null) 
    {
        $dbUser = self::find()
            ->where(["accessToken" => $token])
            ->one();
        if (!count($dbUser)) {
            return null;
        }
        return new static($dbUser);
    }


    public static function findByUsername($username) 
    {
        $dbUser = self::find()
            ->where(["username" => $username])
            ->one();
        if (!count($dbUser)) {
            return null;
        }
        return $dbUser;
    }

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

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

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

配置/ web.php

'user' => [
        'identityClass' => 'app\models\Member',
        'enableAutoLogin' => true,
    ],

我没有更改User.php模型。 这里是:

namespace app\models;

class User extends \yii\base\Object implements \yii\web\IdentityInterface
{
    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;
}
}

您应该确保更改models / LoginForm.php上的getUser()方法以使用您的Member模型类,否则它将继续根据默认的User模型进行验证。

public function getUser() {
    if ($this->_user === false) {
        $this->_user = Member::findByUsername($this->username);
    }
    return $this->_user;
}

另外,这是我自己的User模型类的示例

namespace app\models;

use Yii;

class User extends \yii\db\ActiveRecord implements \yii\web\IdentityInterface {
    const SCENARIO_LOGIN = 'login';
    const SCENARIO_CREATE = 'create';

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

    public function scenarios() {
        $scenarios = parent::scenarios();
        $scenarios[self::SCENARIO_LOGIN] = ['username', 'password'];
        $scenarios[self::SCENARIO_CREATE] = ['username', 'password', 'authKey'];
        return $scenarios;
    }

    public function rules() {
        return [
            [['username', 'email'], 'string', 'max' => 45],
            [['email'], 'email'],
            [['password'], 'string', 'max' => 60],
            [['authKey'], 'string', 'max' => 32],

            [['username', 'password', 'email'], 'required', 'on' => self::SCENARIO_CREATE],
            [['authKey'], 'default', 'on' => self::SCENARIO_CREATE, 'value' => Yii::$app->getSecurity()->generateRandomString()],
            [['password'], 'filter', 'on' => self::SCENARIO_CREATE, 'filter' => function($value) {
                return Yii::$app->getSecurity()->generatePasswordHash($value);
            }],

            [['username', 'password'], 'required', 'on' => self::SCENARIO_LOGIN],

            [['username'], 'unique'],
            [['email'], 'unique'],
            [['authKey'], 'unique'],
        ];
    }

    public function attributeLabels() {
        return [
            'id' => 'Id',
            'username' => 'Username',
            'password' => 'Password',
            'email' => 'Email',
            'authKey' => 'authKey',
        ];
    }

    public static function findIdentity($id) {
        return self::findOne($id);
    }

    public static function findIdentityByAccessToken($token, $type = null) {
        throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
    }

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

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

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

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

    public function validatePassword($password) {
        return Yii::$app->getSecurity()->validatePassword($password, $this->password);
    }
}

确保您实现了IdentityInterface中的方法,但不想使用它引发异常,就像我对findIdentityByAccessToken方法所做的那样。

您应该使用成员类扩展用户类,并在主配置中进行设置:

[...]
'modules' => [
        'user' => [
            'class' => 'member class
            'modelMap' => [
                'User' => 'app\models\member',

更多信息: yii 2:覆盖用户模型

暂无
暂无

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

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