简体   繁体   English

Yii2从DB登录(设置未知属性:app \ models \ User :: password_hash)

[英]Yii2 Login from DB (Setting unknown property: app\models\User::password_hash)

I want the user authentication in Yii to be based on user table in my database. 我希望Yii中的用户身份验证基于我的数据库中的用户表。 This is my User model: 这是我的用户模型:

<?php

namespace app\models;

use Yii;
use yii\base\NotSupportedException;
use yii\db\ActiveRecord;
use yii\helpers\Security;
use yii\web\IdentityInterface;


/**
 * This is the model class for table "user".
 *
 * @property integer $id
 * @property string $username
 * @property string $password
 * @property string $title
 */
class User extends \yii\db\ActiveRecord implements IdentityInterface
{


    public static function tableName()
    {
        return 'user';
    }



    /**
     * @inheritdoc
     */

    public function rules()
    {
        return [
            [['username', 'password'], 'required'],

            [['username', 'password'], 'string', 'max' => 100]           

        ];
    }



    /**
     * @inheritdoc
 */

    public function attributeLabels()
    {
        return [
            'id' => 'UserID',
            'username' => 'Username',
            'password' => 'Password',

        ];

    }   

    public static function findIdentity($id) {

        return static::findOne($id);
    }

    public static function findIdentityByAccessToken($token, $type = null) {
        return static::findOne(['access_token' => $token]);
    }

    public static function findByUsername ($username){

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

    }
    public static function findbyPasswordResetToken($token)
    {
        $expire= \Yii::$app->params['user.passwordResetTokenExpire'];
        $parts = explode('_', $token);
        $timestamp = (int) end($parts);
        if ($timestamp + $expire < time()) {
            //token expired
            return null;

        }
        return static::findOne(['password_reset_token' => $token ]);


    }

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

    public function getAuthKey() {
        return $this->auth_key;
    }

    public function validateAuthKey($authKey) {
        return $this->getAuthKey() === $authKey;
    }

    public function validatePassword($password){
        $this->password_hash= Yii::$app->security->generatePasswordHash ($password);
    }
    public function generateAuthKey()
    {
        $this->auth_key = Yii::$app->security->generateRandomKey();
    }

    /**
     * Generates new password reset token
     */
    public function generatePasswordResetToken()
    {
        $this->password_reset_token = Yii::$app->security->generateRandomKey() . '_' . time();
    }

    /**
     * Removes password reset token
     */
    public function removePasswordResetToken()
    {
        $this->password_reset_token = null;
    }



}

But it is giving me this error when I try to login: 但是当我尝试登录时它会给我这个错误:

Setting unknown property: app\\models\\User::password_hash 设置未知属性:app \\ models \\ User :: password_hash

This is actionLogin in siteController: 这是siteController中的actionLogin:

public function actionLogin()
    {
        if (!\Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            return $this->goBack();
        } else {
            return $this->render('login', [
                'model' => $model,
            ]);
        }
    }

And this is the code in LoginForm.php: 这是LoginForm.php中的代码:

  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);
    } else {
        return false;
    }
}

I don't know what is wrong, could you please help me fix this? 我不知道出了什么问题,请你帮帮我解决这个问题?

This is because the column "password_hash" assigned in the function "validatePassword()" doesn't exist in database or is not declared in the User model. 这是因为函数“validatePassword()”中分配的列“password_hash”在数据库中不存在或未在User模型中声明。

If the password hash is stored in the database in "password" field, then change "validatePassword()" to, 如果密码哈希在“密码”字段中存储在数据库中,则将“validatePassword()”更改为,

public function validatePassword($password)
{
    return $this->password === Yii::$app->security->generatePasswordHash ($password);
}

Here is the solution 1: Declare it in the user controller 这是解决方案1:在用户控制器中声明它

     * @property string $password_hash
        class User extends ActiveRecord implements IdentityInterface
        {
        public $password;

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

  public function rules()
    {
        return [
      [['username','email','first_name','last_name','address','password','contact_no','role'], 'safe'],

                [['email'], 'unique'],
                [['email'], 'email'],

        ];
    }
        .
    .
    ....

         public function validatePassword($password)
        {
            return Yii::$app->security->validatePassword($password, $this->password_hash);
        }

2: In your LoginForm model rule function add this 2:在您的LoginForm模型规则函数中添加此项

['password', 'validatePassword'],

everything else looks okay. 其他一切看起来还不错。 Hope this helps you 希望这对你有所帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM