密码在保存到数据库之前不会进行哈希处理

时间:2017-12-07 12:44:30

标签: javascript node.js mongodb mongoose

我正在使用Node.js,Mongoose,MongoDb,Express开发应用程序。

我尝试在用户注册时保存在数据库中之前对密码进行哈希处理,但它似乎不起作用。密码保存没有散列,有任何建议吗?

'use strict'

  let mongoose = require('mongoose')
  let bcrypt = require('bcrypt-nodejs')
   var Schema = mongoose.Schema

    var userSchema = Schema({
     name: { type: String, required: true, unique: true },
     password: { type: String, required: true },
     createdAt: {
     type: Date,
     require: true,
     default: Date.now
    }
   })
   // check if user already exists
   userSchema.path('name').validate(function (name) {
   User.findOne({name}, function (err, user) {
  if (err) {
  console.log('error')
  } if (user) {
  console.log('The user already exists')
    console.log(user)
  }
  })
}, 'The user already exists')

  // password validation

userSchema.path('password').validate(function (password) {
 return password.length >= 6
 }, 'The password must be of minimum length 6 characters.')
var User = mongoose.model('User', userSchema)

 // hashing and adding salt pre save()

   userSchema.pre('save', function (next) {
    bcrypt.genSalt(10, function (err, salt) {
    if (err) {
     return next(err)
     }
    bcrypt.hash(this.password, salt, null, function (err, hash) {
     // Store hash in your password DB.
    if (err) {
      return next(err)
    }
       // set the password to the hash
      this.password = hash
    })
    next()
 })
 })
  module.exports = User

2 个答案:

答案 0 :(得分:3)

因为你在调用next()回调之前做bcrypt.hash。将next()移至bcrypt.hash回调。

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

    bcrypt.genSalt(10, function(err, salt) {

        if (err) {
            return next(err)
        }

        bcrypt.hash(this.password, salt, null, function(err, hash) {
            // Store hash in your password DB.
            if (err) {
                return next(err)
            }
            // set the password to the hash
            this.password = hash
            next()
        })

    })
})

答案 1 :(得分:2)

使用回调时,应在next()方法中调用

bcrypt.hash()

对于同步:

userSchema.pre('save', (next) => {
   const salt = bcrypt.genSaltSync(10)
   const hash = bcrypt.hashSync(this.password, salt)

   this.password = hash
   next()
})