yii2从DB登录

时间:2015-05-28 13:48:15

标签: php yii yii2

我尝试从DB登录。据我所知,我只需要替换默认模型User。所以我尝试了两次,但在这两种情况下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;
    }
}

2 个答案:

答案 0 :(得分:1)

在配置更改中

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

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

答案 1 :(得分:0)

您还应该实施\yii\web\IdentityInterface。这就是Yii知道如何使用这个类登录你。

正确完成后......

  1. Yii::$app->user将是yii\web\User的实例,而
  2. Yii::$app->user->identity将是app\models\User2
  3. 的一个实例

    ......应该如此。

    <强> P.S:
    另外,请确保从模型类中的\yii\web\IdentityInterface app\models\User2

    实施必要的方法