php - yii2 从数据库登录

标签 php yii yii2

我尝试从数据库登录。据我所知,我只需要替换默认模型用户。所以我尝试了两次,但在这两种情况下 Yii::$app->user->isGuest 都是 true 但必须是 false

LoginForm.php

<?php

namespace app\models;

use Yii;
use yii\base\Model;


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'],
        ];
    }


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

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


    public function login()
    {
        if ($this->validate()) {

            return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0);
        } else {
            return false;
        }
    }


    public function getUser()
    {
        if ($this->_user === false) {
            $this->_user = User::findByUsername($this->username); //default
        #    $this->_user = Users::findByUsername($this->username);//my try 1
        #    $this->_user = Users2::findByUsername($this->username); // my trey 2
        }

        return $this->_user;
    }
}

Users.php

<?php

namespace app\models;

use Yii;


class Users extends \yii\db\ActiveRecord implements \yii\web\IdentityInterface
{
    /**
     * @inheritdoc
     */

    public $authKey;
    public $accessToken;
    public static function tableName()
    {
        return 'users';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name', 'surname', 'login', 'password', 'email'], 'required'],
            [['name', 'surname'], 'string', 'max' => 50],
            [['login'], 'string', 'max' => 20],
            [['password'], 'string', 'max' => 16],
            [['email'], 'string', 'max' => 250]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'name' => 'Name',
            'surname' => 'Surname',
            'login' => 'Login',
            'password' => 'Password',
            'email' => 'Email',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getOrders()
    {
        return $this->hasMany(Orders::className(), ['user_id' => 'id']);
    }
    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([
                "login" => $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;
    }
}

Users2.php

<?php

namespace app\models;

use Yii;


    class Users2 extends \yii\db\ActiveRecord implements \yii\web\IdentityInterface
{

        /**
         * @inheritdoc
         */
        public static function tableName()
        {
            return '2sers';
        }

        /**
         * @inheritdoc
         */
        public function rules()
        {
        return [
            [['id'], 'integer'],
            [['authKey', 'accessToken', 'name', 'surname', 'login', 'password', 'email'], 'required'],
            [['authKey', 'accessToken'], 'string'],
            [['name', 'surname'], 'string', 'max' => 50],
            [['login'], 'string', 'max' => 20],
            [['password'], 'string', 'max' => 16],
            [['email'], 'string', 'max' => 250]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'authKey' => 'Auth Key',
            'accessToken' => 'Access Token',
            'name' => 'Name',
            'surname' => 'Surname',
            'login' => 'Login',
            'password' => 'Password',
            'email' => 'Email',
        ];
    }
    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([
                "login" => $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;
    }
}

最佳答案

在你的配置更改中

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

 'user' => [
        'identityClass' => 'app\models\Users',//or Users2
        'enableAutoLogin' => true,

关于php - yii2 从数据库登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30508467/

相关文章:

database - 根据用户与 master 数据库的 Yii 动态数据库连接

php - 如何编写自定义查询来获取结果数组并进行显示

yii2 - Yii 2安装错误

php - zf2 分页器总数

php - 停止远程服务器 PHP 上的无限循环

php - CSV 文件和数据库

javascript - Yii- 客户端验证不适用于 CActiveForm

elasticsearch - yii2 elasticsearch |确保GET/_nodes

php - Yii2 加载数据本地 INFILE

php - PHP PDO错误处理暂停执行