Yii2使用数据库登录


Yii2 Login with database

我有一个表在我的数据库中称为'成员',我打算存储用户名,密码和所有其他相关信息的用户,我想使用这些用户名/密码登录而不是yii2的默认user .php模型。我已经尝试了将近一天,修改了Member.php模型,但不能使它工作。每次我使用自定义用户名/密码从db,它说用户名或密码是不正确的。有人能帮帮我吗?提前感谢。:)

仅供参考,我在成员表中没有这样的字段,如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/loginfo .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方法。

你应该用你的Member类扩展User类,并在主配置中设置:

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

更多信息:yii 2: override user model