Mongoose password hashing

前端 未结 10 962
盖世英雄少女心
盖世英雄少女心 2020-12-04 07:28

I am looking for a good way to save an Account to MongoDB using mongoose.

My problem is: The password is hashed asynchronously. A setter wont work here because it on

10条回答
  •  春和景丽
    2020-12-04 07:59

    The Mongoose official solution requires the model to be saved before using the verifyPass method, which can cause confusion. Would the following work for you? (I am using scrypt instead of bcrypt).

    userSchema.virtual('pass').set(function(password) {
        this._password = password;
    });
    
    userSchema.pre('save', function(next) {
        if (this._password === undefined)
            return next();
    
        var pwBuf = new Buffer(this._password);
        var params = scrypt.params(0.1);
        scrypt.hash(pwBuf, params, function(err, hash) {
            if (err)
                return next(err);
            this.pwHash = hash;
            next();
        });
    });
    
    userSchema.methods.verifyPass = function(password, cb) {
        if (this._password !== undefined)
            return cb(null, this._password === password);
    
        var pwBuf = new Buffer(password);
        scrypt.verify(this.pwHash, pwBuf, function(err, isMatch) {
            return cb(null, !err && isMatch);
        });
    };
    

提交回复
热议问题