2

I'd like to know how password hash is generated?

// This is my code:

$email="mail@example.net";
$password="mypassword";

// How to get password_hash variable?

$user = User::find()->where(['email'=>$email, 'password_hash'=>$password_hash])->one();
if(isset($user)){
   echo "there is";
} else {
 "Sorry!";  
}

Thank you.

arogachev
  • 33,150
  • 7
  • 114
  • 117
Nedim
  • 563
  • 1
  • 11
  • 23
  • `User::find()->where(['email'=>$email, 'password_hash'=>$password_hash])->one();` This habit does not secure with sql injection. We should find model then call validatePassword function to validate user model. Reference Pheagey's answer. – Ngô Văn Thao Jul 02 '15 at 04:24

3 Answers3

2

http://www.yiiframework.com/doc-2.0/guide-security-passwords.html Is how passwords are handled in Yii 2. Unless you're a crypto expert DO NOT try to write your own.

David J Eddy
  • 1,999
  • 1
  • 19
  • 37
0
  public function verifyPassword($password)
    {
        if(md5($password) === $this->password)
            return TRUE;
        else
            return FALSE;
        //return Yii::$app->security->validatePassword($password, $this->password);
    }

  public function beforeSave($insert)
    {
        // hash new password if set
        if ($this->newPassword) {
            //$this->password = Yii::$app->security->generatePasswordHash($this->newPassword);
            $this->password = md5($this->newPassword);
        }

        // convert ban_time checkbox to date
        if ($this->ban_time) {
            $this->ban_time = date("Y-m-d H:i:s");
        }

        // ensure fields are null so they won't get set as empty string
        $nullAttributes = ["email", "username", "ban_time", "ban_reason"];
        foreach ($nullAttributes as $nullAttribute) {
            $this->$nullAttribute = $this->$nullAttribute ? $this->$nullAttribute : null;
        }

        return parent::beforeSave($insert);
    }
-4

I use hash with md5 but i create function in user model

    public function validatePassword($password)
{
    return $this->PASSWORD === md5($password);
}
Nuengnapa
  • 117
  • 1
  • 6
  • 1
    md5 is highly insecure. I would either use PHP's new built-in password_hash function or yii\base\Security::generatePasswordHash. – Justin Cherniak Dec 29 '14 at 06:35
  • 1
    This is the answer: `$user = User::find()->where(['email'=>$email])->one(); if(!$user){ // Wrong email } elseif (!Yii::$app->security->validatePassword($password, $user->password_hash)) { // Invalid password } else { // Ok }` – Nedim Dec 29 '14 at 07:44
  • ...Please tell me you no longer do this. Use the built in crypto methods. MD5 will get you compromised. A simple MD4/SHA1 hash is no longer a secure form of encryption. – David J Eddy Aug 18 '15 at 15:41