0
votes

Newbie and learning yii2. I have a custom database of users that I want to use as my login credential and luckily I was able to query it, however on my public static function validatePassword($password), I am getting a Using $this when not in object context.

Here is my code

public static function findByUsername($username)
{
   $user = self::find()->where(['USR_USERNAME' => $username, 'USR_STATUS' => '1'])->one();
   return new static($user);
}

public function getId()
{
    return $this->id;
}

/**
 * {@inheritdoc}
 */


public static function validatePassword($password)
{
    return $this->password === $password;
}

and here is the screenshot of my error. enter image description here

all the script was generated using gii module, so I do not know why is it producing this error, also upon watching tutorials I copy their code but not working on my end. Please help, thank you.

As requested here is the DbUser.php code

<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "{{%RBAC_USERS}}".
 *
 * @property string $USR_UID
 * @property string $USR_USERNAME
 * @property string $USR_PASSWORD
 * @property string $USR_FIRSTNAME
 * @property string $USR_LASTNAME
 * @property string $USR_EMAIL
 * @property string $USR_DUE_DATE
 * @property string $USR_CREATE_DATE
 * @property string $USR_UPDATE_DATE
 * @property int $USR_STATUS
 * @property string $USR_AUTH_TYPE
 * @property string $UID_AUTH_SOURCE
 * @property string $USR_AUTH_USER_DN
 * @property string $USR_AUTH_SUPERVISOR_DN
 */
class DbUsers extends \yii\db\ActiveRecord implements \yii\web\IdentityInterface

{

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%RBAC_USERS}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['USR_UID', 'USR_DUE_DATE'], 'required'],
            [['USR_DUE_DATE', 'USR_CREATE_DATE', 'USR_UPDATE_DATE'], 'safe'],
            [['USR_STATUS'], 'integer'],
            [['USR_UID', 'USR_AUTH_TYPE', 'UID_AUTH_SOURCE'], 'string', 'max' => 32],
            [['USR_USERNAME', 'USR_EMAIL'], 'string', 'max' => 100],
            [['USR_PASSWORD'], 'string', 'max' => 128],
            [['USR_FIRSTNAME', 'USR_LASTNAME'], 'string', 'max' => 50],
            [['USR_AUTH_USER_DN', 'USR_AUTH_SUPERVISOR_DN'], 'string', 'max' => 255],
            [['USR_UID'], 'unique'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'USR_UID' => Yii::t('app', 'Uid'),
            'USR_USERNAME' => Yii::t('app', 'Username'),
            'USR_PASSWORD' => Yii::t('app', 'Password'),
        ];
    }


    /**
     * {@inheritdoc}
     */
    public static function findIdentity($id)
    {
        throw new NotSupportedException();
    }

    /**
     * {@inheritdoc}
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {

        throw new NotSupportedException();
    }

    /**
     * Finds user by username
     *
     * @param string $username
     * @return static|null
     */
    public function getAuthKey()
    {
        throw new NotSupportedException();
    }

    /**
     * {@inheritdoc}
     */
    public function validateAuthKey($authKey)
    {
        throw new NotSupportedException();
    }

    public static function findByUsername($username, $password)
    {
        $user = self::find()->where(['USR_USERNAME' => $username, 'USR_STATUS' => '1'])->one();

        return $user;


    }

    public function getId()
    {
        return $this->getPrimaryKey();
    }

    /**
     * {@inheritdoc}
     */


    public static function validatePassword($password)
    {
        return $this->password === $password;
    }


}

Here is my LoginForm.php

<?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 = false;

    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 = DbUsers::findByUsername($this->username, $this->password);
        }

        return $this->_user;
    }
}
4

4 Answers

3
votes

In static function you can't use $this. make validatePassword() function non-static.

1
votes

You can not use $this with static function, change to

public function validatePassword($password)
{
   return $this->password === $password;
}
-1
votes

Please update your question, add a DbUsers model code. Where the method validatePassword() was executed? And of course, you cannot use $this in static method, make the method not static

-1
votes

I answer my own question. I added the following code in the find

  public static function findByUsername($username, $password)
    {
        $user = self::find()->where(['USR_USERNAME' => $username, 'USR_STATUS' => '1'])->one();

        if (hash('sha256', $password) == $user->USR_PASSWORD)
        {
            return new static($user);
        }


    }

now this will validate if the password is matched with the database in sha256 encryption and then on my validatePassword method I revise it to simple always return true because, on the LoginForm, they always search for the username first then check for the password validation, so If username/password is wrong it will instantly validate the user doens't exist

 public static function validatePassword($password)
    {
        return true;
    }

I find yii2 hard, very hard with the lack of documentation.