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
Ich zog es ist nichts passiert! Gibt es noch etwas, was ich tun sollte? benötigt es in server.js vielleicht? – sasuri
Ja, versuche, 'var zu verschieben User = mongoose.model ('User', userSchema)' genau über 'module.exports = User' und unter' userSchema.pre (... ' – Stamos
danke, es hat funktioniert! – sasuri