trouble with login from DB. , $this->password === null

I try to make authentication from DB.

  1. I have created DB - script is placed below

  2. I have created model models/Users.php

  3. I have changed model models/LoginForm.php and config/web.php (and config/db.php for connect to DB)

But id doesn’t work.

I found out that inside my function validatePassword() $this->password === null. Also another properties of $this-> === null.

But self::getAttribute("password") inside this function is not null and return password from DB. Also another attributes self::getAttribute( is not null

Please, who know, write me what i did wrong.

I place here SQL script and modules which I changed

DB


set names utf8;


drop table if exists users;


CREATE TABLE users(

  id int NOT NULL AUTO_INCREMENT PRIMARY KEY,

  firstName varchar(30),

  lastName varchar(30),

  username varchar(30) NOT NULL,

  password varchar(30) NOT NULL,

  authKey varchar(50) NOT NULL comment 'Auth key column required for cookie based login. Should be unique for every user',

  accessToken varchar(50) NOT NULL,

  role int NOT NULL

);


insert into users(firstName, lastName, username, password, authKey, accessToken, role)

values('Олександр', 'Шинк...','alex','alex','key1','token1',1);

My model Users.php


<?php


namespace app\models;


use Yii;


use yii\web\IdentityInterface;




class Users extends \yii\db\ActiveRecord implements \yii\web\IdentityInterface

{

	public $id;

	public $firstName;

	public $lastName;

	public $username;

	public $password;

	public $authKey;

	public $accessToken;

	public $role;

	

    /**

     * @inheritdoc

     */

    public static function tableName()

    {

        return 'users';

    }


    /**

     * @inheritdoc

     */

    public function rules()

    {

        return [

            [['username', 'password', 'authKey', 'accessToken', 'role'], 'required'],

            [['role'], 'integer'],

            [['firstName', 'lastName', 'username', 'password'], 'string', 'max' => 30],

            [['authKey', 'accessToken'], 'string', 'max' => 50]

        ];

    }


    /**

     * @inheritdoc

     */

    public function attributeLabels()

    {

        return [

            'id' => 'ID',

            'firstName' => 'First Name',

            'lastName' => 'Last Name',

            'username' => 'Username',

            'password' => 'Password',

            'authKey' => 'Auth Key',

            'accessToken' => 'Access Token',

            'role' => 'Role',

        ];

    }

    

    public static function findIdentity($id)

    {

    	return self::findOne($id);

    	

    }

    

    public static function findIdentityByAccessToken($token, $type = null)

    {

    	throw new NotSupportedException("");

    }

    

    public function getId()

    {

    	return $this->id;

    }

    

    public function getAuthKey()

    {

    	return $this->authKey;

    }

    

    public function validateAuthKey($authKey)

    {

    	return $this->authKey === $authKey;

    }

    

    public static function findByUsername($username)

    	return self::findOne(['username' => $username]);

    	

    }

    

    public function validatePassword($password)

    {

		///не работает потому что $this->password === null

		//return $this->password === $password;  /

		

		

		//но так работает

    	return $password === self::getAttribute("password");

    }    

    

    

}



LoginForm.php - method getUser() was changed


<?php


namespace app\models;


use Yii;


use yii\base\Model;


/**

 * LoginForm is the model behind the login form.

 */

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

        ];

    }


    /**

     * Validates the password.

     * This method serves as the inline validation for password.

     *

     * @param string $attribute the attribute currently being validated

     * @param array $params the additional name-value pairs given in the rule

     */

    public function validatePassword($attribute, $params)

    {

        if (!$this->hasErrors()) {


            $user = $this->getUser();


            if (!$user || !$user->validatePassword($this->password)) {

                $this->addError($attribute, 'Incorrect username or password.');

            }

        }

    }


    /**

     * Logs in a user using the provided username and password.

     * @return boolean whether the user is logged in successfully

     */

    public function login()

    {

        if ($this->validate()) {

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

        }

        return false;

    }


    /**

     * Finds user by [[username]]

     *

     * @return User|null

     */

    public function getUser()

    {

        if ($this->_user === false) {

            $this->_user = Users::findByUsername($this->username);

        }

        return $this->_user;

    }

}

web.php -


<?php


$params = require(__DIR__ . '/params.php');


$config = [

    'id' => 'basic',

    'basePath' => dirname(__DIR__),

    'bootstrap' => ['log'],

    'components' => [

        'request' => [

            // !!! insert a secret key in the following (if it is empty) - this is required by cookie validation

            'cookieValidationKey' => 'login',

        ],

        'cache' => [

            'class' => 'yii\caching\FileCache',

        ],

        'user' => [

            'identityClass' => 'app\models\Users',

            'enableAutoLogin' => false,

        ],

        'errorHandler' => [

            'errorAction' => 'site/error',

        ],

        'mailer' => [

            'class' => 'yii\swiftmailer\Mailer',

            // send all mails to a file by default. You have to set

            // 'useFileTransport' to false and configure a transport

            // for the mailer to send real emails.

            'useFileTransport' => true,

        ],

        'log' => [

            'traceLevel' => YII_DEBUG ? 3 : 0,

            'targets' => [

                [

                    'class' => 'yii\log\FileTarget',

                    'levels' => ['error', 'warning'],

                ],

            ],

        ],

        'db' => require(__DIR__ . '/db.php'),

        /*

        'urlManager' => [

            'enablePrettyUrl' => true,

            'showScriptName' => false,

            'rules' => [

            ],

        ],

        */

    ],

    'params' => $params,

];


if (YII_ENV_DEV) {

    // configuration adjustments for 'dev' environment

    $config['bootstrap'][] = 'debug';

    $config['modules']['debug'] = [

        'class' => 'yii\debug\Module',

    ];


    $config['bootstrap'][] = 'gii';

    $config['modules']['gii'] = [

        'class' => 'yii\gii\Module',

    ];

}


return $config;

What’s the problem? What exactly doesn’t work?

In the above case I get message "Incorrect username or password" because of $this->password===null in a function validatePassword($password) in my module Users.php

But now I found out that it was caused by declaration in my module


public $id;

	public $firstName;

	public $lastName;

	public $username;

	public $password;

	public $authKey;

	public $accessToken;

	public $role;

I deleted it and now the function validatePassword works correctly and I don’t get above message.

But now I have a new problem. After login I don’t see that I logged in as a defined user, for example like standart(basic) users: admin/admin or demo/demo.

I continue to watch link login but not logout(user_name)