【问题标题】:Password doesn't hash before being saved into the db密码在保存到数据库之前不会散列
【发布时间】:2017-12-07 12:44:30
【问题描述】:

我正在使用 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

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    这是因为你在调用bcrypt.hash 回调之前执行了next()。将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()
            })
    
        })
    })
    

    【讨论】:

    • 我搬了它什么也没发生!还有什么我应该做的吗?在 server.js 中可能需要它?
    • 是的,请尝试将var User = mongoose.model('User', userSchema) 移动到module.exports = User 上方和userSchema.pre(... 下方
    【解决方案2】:

    next() 应在使用回调时在bcrypt.hash() 方法中调用。

    对于同步:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-05
      • 2017-01-22
      • 1970-01-01
      • 2012-02-10
      • 2012-02-10
      • 2011-04-28
      • 2019-11-01
      相关资源
      最近更新 更多