2017-12-07 5 views
2

Ich entwickle eine App mit Node.js, Mongoose, MongoDb, Express.Passwort nicht Hash vor dem Speichern in der db

Ich versuche, das Passwort vor dem Speichern in der db hash, wenn der Benutzer registrieren, aber es scheint nicht zu funktionieren. Das Passwort wird ohne Hashing gespeichert, irgendwelche Vorschläge?

'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 

Antwort

3

Sein, weil Sie next() vor bcrypt.hash Rückruf aufgerufen wird. Verschieben Sie next() in bcrypt.hash Rückruf.

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

    }) 
}) 
+0

Ich zog es ist nichts passiert! Gibt es noch etwas, was ich tun sollte? benötigt es in server.js vielleicht? – sasuri

+1

Ja, versuche, 'var zu verschieben User = mongoose.model ('User', userSchema)' genau über 'module.exports = User' und unter' userSchema.pre (... ' – Stamos

+0

danke, es hat funktioniert! – sasuri

2

next() sollte innerhalb bcrypt.hash() Methode aufgerufen werden, wenn Rückrufe verwendet.

Für synchrone:

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

    this.password = hash 
    next() 
})