散列和加盐密码字段

hashing and salting password field

我正在尝试对密码进行散列和加盐处理,但出现了很多错误! 该代码有什么问题或正确的输入方式是什么?

user.js代码

const mongoose = require('mongoose')
const schema = mongoose.Schema
const promise = require('bluebird')
const bcrypt = promise.promisifyAll(require('bcrypt'))

function hashPassword(user, option) {
  const SALT_FACTOR = 8

  if (!user.isModified('password')) {
    return;
   }

  return bcrypt
    .genSaltAsync(SALT_FACTOR)
    .then(salt => bcrypt.hashAsync(user.password, salt, null))
    .then(hash => {
      user.setDataValue('password', hash)
    })
}

// create schema and model
const userSchema = new schema({

    email: {
      type: String,
      required: true,
      unique: true
    },
    password: {
      type: String,
      required: true
    }

})

userSchema.pre('create', function(next) {
   hashPassword()

})

userSchema.pre('update', function(next) {
   hashPassword()

})

userSchema.pre('save', function(next) {
   hashPassword()

})

const user = mongoose.model('user', userSchema)

user.prototype.compairePassword = function (password) {
  return bcrypt.compareAsync(password, this.password)
}

module.exports = user
const mongoose = require('mongoose')
const schema = mongoose.Schema
const promise = require('bluebird')
const bcrypt = promise.promisifyAll(require('bcrypt'))
const SALT_WORK_FACTOR = 10

// create schema and model
const userSchema = new schema({

    email: {
      type: String,
      required: true,
      unique: true
    },
    password: {
      type: String,
      required: true
    }

})

userSchema.pre('save', function(next) {
    const user = this

    // only hash the password if it has been modified (or is new)
    if (!user.isModified('password')) return next()

    // generate a salt
    bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
        if (err) return next(err)

        // hash the password using our new salt
        bcrypt.hash(user.password, salt, function(err, hash) {
            if (err) return next(err)

            // override the cleartext password with the hashed one
            user.password = hash
            next()
        })
    })
})

userSchema.methods.comparePassword = function(candidatePassword, cb) {
    bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {
        if (err) return cb(err);
        cb(null, isMatch);
    })
}


const user = mongoose.model('user', userSchema)

module.exports = user