Incorrect username or password.

Hello I’m new to Yii , I’m using Yii2 basic, I tried to create login with database but I did’t yet get it I get error : Incorrect username or password.

my model is :




<?php


namespace app\models;


use Yii;


/**

 * This is the model class for table "user_login".

 *

 * @property integer $id

 * @property string $username

 * @property string $password

 * @property string $authKey

 * @property string $accessToken

 * @property integer $USERS_ID

 *

 */

 

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

{

    public $id;

    public $username;

    public $password;

    public $authKey;

    public $accessToken;


	

	/////////////////////////////////////////////////////////////////////////////////////////////////////////////

	/**

     * @inheritdoc

     */

    public static function tableName()

    {

        return 'user_login';

    }


    /**

     * @inheritdoc

     */

    public function rules()

    {

        return [

            [['username', 'password', 'USERS_ID'], 'required'],

            [['USERS_ID'], 'integer'],

            [['username', 'password', 'authKey', 'accessToken'], 'string', 'max' => 25],

            [['USERS_ID'], 'exist', 'skipOnError' => true, 'targetClass' => Users::className(), 'targetAttribute' => ['USERS_ID' => 'USERS_ID']],

        ];

    }


    /**

     * @inheritdoc

     */

    public function attributeLabels()

    {

        return [

            'id' => 'ID',

            'username' => 'Name',

            'password' => 'Password',

            'authKey' => 'Auth Key',

            'accessToken' => 'Access Token',

            'USERS_ID' => 'Users ID',

        ];

    }

	

	/////////////////////////////////////////////////////////////////////////////////////////////////////////////

	


    /**

     * @inheritdoc

     */

    public static function findIdentity($id)

    {

		

		return self::findOne($id);

    }


    /**

     * @inheritdoc

     */

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

    {

		

		throw new yii\base\NotSupportedException();

    }


    /**

     * Finds user by username

     *

     * @param string $username

     * @return static|null

     */

    public static function findByUsername($username)

    {

		

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

		

    }


    /**

     * @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 bool if password provided is valid for current user

     */

    public function validatePassword($password)

    {

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

    }

}




and my login form is




<?php


namespace app\models;


use Yii;

use yii\base\Model;


/**

 * LoginForm is the model behind the login form.

 *

 * @property User|null $user This property is read-only.

 *

 */

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 bool 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 = UserLogin::findByUsername($this->username); 

        }


        return $this->_user;

    }

}




Hi Bynd, welcome to the forum.

So you already have ‘user_login’ table.

What columns does it have? Does it have ‘id’, ‘username’, ‘password’, ‘authKey’, ‘accessToken’ and ‘USERS_ID’? If it does, then you don’t have to (or, rather, should not) declare them as the public variables of the class.




/**

 * This is the model class for table "user_login".

 *

 * @property integer $id

 * @property string $username

 * @property string $password

 * @property string $authKey

 * @property string $accessToken

 * @property integer $USERS_ID

 *

 */

 

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

{

    // public $id;

    // public $username;

    // public $password;

    // public $authKey;

    // public $accessToken;


    /**

     * @inheritdoc

     */

    public static function tableName()

    {

        return 'user_login';

    }

...



If you have ‘auth_key’ and ‘access_token’ instead of ‘authKey’ and ‘accessToken’, then the code should be changed accordingly:




/**

 * This is the model class for table "user_login".

 *

 * @property integer $id

 * @property string $username

 * @property string $password

 * @property string $auth_key      // changed

 * @property string $access_token  // changed

 * @property integer $USERS_ID

 *

 */

 

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

{

    /**

     * @inheritdoc

     */

    public static function tableName()

    {

        return 'user_login';

    }


    /**

     * @inheritdoc

     */

    public function rules()

    {

        return [

            [['username', 'password', 'USERS_ID'], 'required'],

            [['USERS_ID'], 'integer'],

            [['username', 'password', 'auth_key', 'access_token'], 'string', 'max' => 25],  // changed

            [['USERS_ID'], 'exist', 'skipOnError' => true, 'targetClass' => Users::className(), 'targetAttribute' => ['USERS_ID' => 'USERS_ID']],

        ];

    }


    /**

     * @inheritdoc

     */

    public function attributeLabels()

    {

        return [

            'id' => 'ID',

            'username' => 'Name',

            'password' => 'Password',

            'auth_key' => 'Auth Key',  // changed

            'access_token' => 'Access Token',  // changed

            'USERS_ID' => 'Users ID',

        ];

    }

...

    /**

     * @inheritdoc

     */

    public function getAuthKey()

    {

        return $this->auth_key;  // changed

    }


    /**

     * @inheritdoc

     */

    public function validateAuthKey($authKey)

    {

        return $this->auth_key === $authKey; // changed

    }


...



Note that all the columns of the table can be accessed directly using their column names without explicitly declaring them as the public variables in ActiveRecord.

1st Thank you for your answer, I did remove

public &#036;id; public &#036;username;  public &#036;password; public &#036;authKey; and public &#036;accessToken;

I didn’t change ‘authKey’ and ‘accessToken’ because I have ‘authKey’ and ‘accessToken’; in my database but I still can’t login now when I click the login button it go to home page but it didn’t login me I don’t know why

Does your ‘user_login’ table contains a valid set of ‘username’ and ‘password’?

Yes I have you can see in the attached files

I see.

Then let’s debug.




    public function validatePassword($attribute, $params)

    {

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

            $user = $this->getUser();

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

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

//          }

            if (!$user) {

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

            } else {

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

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

                 }

            }

        }

    }



I tried this function but nothing happened , but I used var dump the $params is NULL here are the results i get are


public function validatePassword($attribute, $params)

    {

		var_dump ($this->username);

		die();

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

            $user = $this->getUser();

            if (!$user) {

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

				  

            } else {

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

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

                 }

            } 

        }

    }

result : I:\zzerver\Uwamp -port 84\uw-cms-p8585\www\yii22\wfp\models\LoginForm.php:47:string ‘logger1’ (length=7);


public function validatePassword($attribute, $params)

    {

		var_dump ($this->password);

		die();

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

            $user = $this->getUser();

            if (!$user) {

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

				  

            } else {

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

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

                 }

            } 

        }

    }

result : I:\zzerver\Uwamp -port 84\uw-cms-p8585\www\yii22\wfp\models\LoginForm.php:47:string ‘123456’ (length=6)


public function validatePassword($attribute, $params)

    {

		var_dump ($attribute);

		die();

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

            $user = $this->getUser();

            if (!$user) {

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

				  

            } else {

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

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

                 }

            } 

        }

    }

result : I:\zzerver\Uwamp -port 84\uw-cms-p8585\www\yii22\wfp\models\LoginForm.php:47:string ‘password’ (length= 8 )


public function validatePassword($attribute, $params)

    {

		var_dump ($params);

		die();

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

            $user = $this->getUser();

            if (!$user) {

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

				  

            } else {

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

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

                 }

            } 

        }

    }

result : I:\zzerver\Uwamp -port 84\uw-cms-p8585\www\yii22\wfp\models\LoginForm.php:47:null

Ah, OK. I think I got it.

It’s probably because of “USERS_ID” which requires to be a valid foreign key to ‘users’ table.




    public function validatePassword($attribute, $params)

    {

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

            $user = $this->getUser();

            if (!$user) {

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

            } else {

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

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

                 }

            }

        } else {

            var_dump($this->errors);

        }

    }



still nothing change it show nothing; but I did var_dump on this function because you said about id but nothing happen no message no result nothing


public static function findIdentity($id)

    {

		var_dump($id);

		die();

		return self::findOne($id);

    }

I did also


public static function findIdentity($id)

    {

		var_dump('hello');

		die();

		return self::findOne($id);

    }

But nothing happen I didn’t get the Hello

Some thing strange is that I did insert a wrong password and it says " Incorrect username or password." , BUT if I insert correct username and correct password it go back to home page but I’m not logged in this is the page it give me when I insert correct username and correct password, I did draw a red line to show you that the login is still there and if I press login I got to login form

Check the ‘user’ and ‘session’ components of your app.

where can I check that this is my console config


$db = require __DIR__ . '/db.php';


$config = [

    'id' => 'basic-console',

    'basePath' => dirname(__DIR__),

    'bootstrap' => ['log'],

    'controllerNamespace' => 'app\commands',

    'components' => [

        'cache' => [

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

        ],

        'log' => [

            'targets' => [

                [

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

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

                ],

            ],

        ],

        'db' => $db,

    ],

    'params' => $params,

    /*

    'controllerMap' => [

        'fixture' => [ // Fixture generation command line.

            'class' => 'yii\faker\FixtureController',

        ],

    ],

    */

];


if (YII_ENV_DEV) {

    // configuration adjustments for 'dev' environment

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

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

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

    ];

}


return $config;



and this is my web config


<?php


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

$db = require __DIR__ . '/db.php';


$config = [

    'id' => 'basic',

    'basePath' => dirname(__DIR__),

    'bootstrap' => ['log'],

    'aliases' => [

        '@bower' => '@vendor/bower-asset',

        '@npm'   => '@vendor/npm-asset',

    ],

    'components' => [

        'request' => [

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

            'cookieValidationKey' => 'sAxQzCbivYgPrGX5wgM8aeePY5xuRTkr',

        ],

        'cache' => [

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

        ],

        'user' => [

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

            'enableAutoLogin' => true,

        ],

        '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' => $db,

        /*

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

        // uncomment the following to add your IP if you are not connecting from localhost.

        //'allowedIPs' => ['127.0.0.1', '::1'],

    ];


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

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

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

        // uncomment the following to add your IP if you are not connecting from localhost.

        //'allowedIPs' => ['127.0.0.1', '::1'],

    ];

}


return $config;



‘identityClass’ should be ‘app\models\UserLogin’.

YAHOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO

You are genius, Thank you very much.