简体   繁体   中英

Password doesn't hash before being saved into the db

I'm developing an app using Node.js, Mongoose, MongoDb, Express.

I'm trying to hash the password before being saved in the db when the user register, but it doesn't seems to work. The password is saved without hashing, any suggestions?

'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

Its because you do next() before bcrypt.hash callback is called. Move next() into bcrypt.hash callback.

 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()
        })

    })
})

next() should be called within bcrypt.hash() method when using callbacks.

For synchronous:

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

   this.password = hash
   next()
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM