Yii2 login from DB

I am trying to make a login from DB. As I understand it, for this I just need to replace the default User model. So I try this twice, but in both cases Yii::$app->user->isGuest

there is true

but should befalse

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

      

+3


source to share


2 answers


In your configuration change

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

      



For

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

      

+1


source


You must also implement \yii\web\IdentityInterface

. This is how Yii knows how you can use this class.

If done correctly ...

  • Yii::$app->user

    will be an instance yii\web\User

    and
  • Yii::$app->user->identity

    will be an instance app\models\User2



... as it should be.

PS :.
Also don't forget to implement the required methods from \yii\web\IdentityInterface

in your model class,app\models\User2

0


source







All Articles