Yii Framework Forum: Incorrect username or password. - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

Incorrect username or password. Rate Topic: -----

#1 User is offline   Bynd 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 32
  • Joined: 16-December 17

Posted 19 December 2017 - 04:32 AM

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


0

#2 User is offline   softark 

  • Keep It Simple
  • Yii
  • Group: Moderators
  • Posts: 3,623
  • Joined: 16-February 11
  • Location:Japan

Posted 19 December 2017 - 06:47 AM

Hi Bynd, welcome to the forum.

View PostBynd, on 19 December 2017 - 04:32 AM, said:

<?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';
    }
...



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.
1

#3 User is offline   Bynd 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 32
  • Joined: 16-December 17

Posted 19 December 2017 - 11:26 AM

View Postsoftark, on 19 December 2017 - 06:47 AM, said:


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 $id; public $username; public $password; public $authKey; and public $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
0

#4 User is offline   softark 

  • Keep It Simple
  • Yii
  • Group: Moderators
  • Posts: 3,623
  • Joined: 16-February 11
  • Location:Japan

Posted 20 December 2017 - 05:57 AM

Does your 'user_login' table contains a valid set of 'username' and 'password'?
1

#5 User is offline   Bynd 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 32
  • Joined: 16-December 17

Posted 20 December 2017 - 11:25 AM

View Postsoftark, on 20 December 2017 - 05:57 AM, said:

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


Yes I have you can see in the attached files

Attached File(s)


0

#6 User is offline   softark 

  • Keep It Simple
  • Yii
  • Group: Moderators
  • Posts: 3,623
  • Joined: 16-February 11
  • Location:Japan

Posted 20 December 2017 - 06:05 PM

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.');
                 }
            }
        }
    }

0

#7 User is offline   Bynd 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 32
  • Joined: 16-December 17

Posted 20 December 2017 - 07:37 PM

View Postsoftark, on 20 December 2017 - 06:05 PM, said:

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
0

#8 User is offline   softark 

  • Keep It Simple
  • Yii
  • Group: Moderators
  • Posts: 3,623
  • Joined: 16-February 11
  • Location:Japan

Posted 20 December 2017 - 07:53 PM

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

0

#9 User is offline   Bynd 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 32
  • Joined: 16-December 17

Posted 20 December 2017 - 08:05 PM

View Postsoftark, on 20 December 2017 - 07:53 PM, said:

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
0

#10 User is offline   Bynd 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 32
  • Joined: 16-December 17

Posted 20 December 2017 - 08:17 PM

View Postsoftark, on 20 December 2017 - 07:53 PM, said:

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



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

Attached File(s)


0

#11 User is offline   softark 

  • Keep It Simple
  • Yii
  • Group: Moderators
  • Posts: 3,623
  • Joined: 16-February 11
  • Location:Japan

Posted 20 December 2017 - 09:19 PM

Check the 'user' and 'session' components of your app.
0

#12 User is offline   Bynd 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 32
  • Joined: 16-December 17

Posted 20 December 2017 - 10:14 PM

View Postsoftark, on 20 December 2017 - 09:19 PM, said:

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;

0

#13 User is offline   softark 

  • Keep It Simple
  • Yii
  • Group: Moderators
  • Posts: 3,623
  • Joined: 16-February 11
  • Location:Japan

Posted 20 December 2017 - 11:04 PM

View PostBynd, on 20 December 2017 - 10:14 PM, said:

and this is my web config

<?php
        'user' => [
            'identityClass' => 'app\models\User',
            'enableAutoLogin' => true,
        ],



'identityClass' should be 'app\models\UserLogin'.
1

#14 User is offline   Bynd 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 32
  • Joined: 16-December 17

Posted 21 December 2017 - 10:56 AM

View Postsoftark, on 20 December 2017 - 11:04 PM, said:

'identityClass' should be 'app\models\UserLogin'.



YAHOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO

You are genius, Thank you very much.
0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users