user5534204
user5534204

Reputation:

Store password as hash using yii

How can I store password as hash?

<?php

class StudentRegisterForm extends CActiveRecord {

public $email;
public $password;
public $studentName;
public $academicYear;
public $moduleName;
private $_identity;

/**
 * Declares the validation rules.
 * The rules state that username and password are required,
 * and password needs to be authenticated.
 */
public static function model($className = __CLASS__) {
    return parent::model($className);
}

public function tableName() {
    return '{{students}}';
}

public function rules() {
    return array(
        // username and password are required
        array('email, password,studentName,academicYear,moduleName', 'required'),
    );
}

/**
 * Declares attribute labels.
 */
public function attributeLabels() {
    return array(
        'id' => 'Id',
        'email' => 'Email',
        'password' => 'Password',
        'studentName' => 'Student Name',
        'academicYear' => 'Acadamic Year',
        'moduleName' => 'Module Name',
    );
}

    /**
 * Checks if the given password is correct.
 * @param string the password to be validated
 * @return boolean whether the password is valid
 */
public function validatePassword($password) {
    return CPasswordHelper::verifyPassword($password, $this->password);
}

/**
 * Generates the password hash.
 * @param string password
 * @return string hash
 */
public function hashPassword($password) {
    return CPasswordHelper::hashPassword($password);
}

//     * This is invoked before the record is saved.
//     * @return boolean whether the record should be saved.
public function beforeSave() 
{
    if (parent::beforeSave()) {

        return true;
    }
    else
        return false;
}

//     * This is invoked after the record is saved.

public function afterSave() {
    parent::afterSave();
}
}

Upvotes: 1

Views: 66

Answers (2)

Anway Kulkarni
Anway Kulkarni

Reputation: 261

You can directly use this function for creating a hash password in yii2

 $password = Yii::$app->security>generatePasswordHash($password_string);

and for validating the password use

Yii::$app->getSecurity()->validatePassword($password_string,  $password)

Upvotes: 1

Amitesh Kumar
Amitesh Kumar

Reputation: 3079

call this below function :

public function hashPassword($password) {
    return CPasswordHelper::hashPassword($password);
}

in before save method , then you can store the password in hash.

Upvotes: 0

Related Questions