2017-03-09 71 views
0

由于某些原因,当我尝试散列并保存密码时,新密码不会保存到数据库中?我正在使用MongoDB,NodeJS和护照让用户更改密码。稍微Bcrypt不保存密码?

app.post('/reset/:token', function(req, res) { 
    async.waterfall([ 
    function(done) { 
     User.findOne({ resetPasswordToken: req.params.token, resetPasswordExpires: { $gt: Date.now() } }, function(err, user, next) { 
     if (!user) { 
      req.flash('error', 'Password reset token is invalid or has expired.'); 
      return res.redirect('back'); 
     } 


     user.password = req.body.password; 
     user.resetPasswordToken = undefined; 
     user.resetPasswordExpires = undefined; 
     console.log('password' + user.password + 'and the user is' + user) 

    user.save(function(err) { 
    if (err) { 
     console.log('here') 
     return res.redirect('back'); 
    } else { 
     console.log('here2') 
    req.logIn(user, function(err) { 
     done(err, user); 
    }); 

    } 
     }); 
     }); 
    }, 

回答

0

重塑它:

UserSchema.pre('save', function(next) { 
    var user = this; 
    var SALT_FACTOR = 5; 
console.log('trying to save the password') 

    if (!user.isModified('password')) return next(); 

    bcrypt.genSalt(SALT_FACTOR, function(err, salt) { 
    if (err) return next(err); 

bcrypt.hash(user.password, salt, function(err, hash) { 
    if (err) return next(err); 
    user.password = hash; 
    next(); 
}); 
}); 
}); 

发布保存。移动用户更新功能的型号,所以你就会有一个user.js的文件,这是一个有点像这样(如型号/ user.js的):

var mongoose = require('mongoose'); 
var bcrypt = require('bcrypt'); 
var db = mongoose.connection; 

var UserSchema = mongoose.Schema({ 
    email: { 
     type: String 
    }, 
    password: { 
     type: String, 
     required: true, 
     bcrypt: true 
    } 
    // more fields etc 
}); 

var User = module.exports = mongoose.model('User', UserSchema); 

module.exports.updateUser = function(newUser, userId, callback) { 
    if (newUser.password != "" && newUser.password != undefined) { 
     bcrypt.hash(newUser.password,10,function(err,hash){ 
      if (err) throw err; 
      newUser.password = hash; 
      var upsertData = newUser.toObject(); 
      delete upsertData._id; 
      User.update({_id: userId}, upsertData, {upsert:true}, callback); 
     }); 
    } else { 
     var upsertData = newUser.toObject(); 
     delete upsertData._id; 
     delete upsertData.password; 
     User.update({_id: userId}, upsertData, {upsert:true}, callback); 
    }; 
} 

然后在你的路由/应用程序文件就可以了包括我猜你就是这么做的用户模型(例如路由/ user.js的):

var User = require('../models/user'); 

,并使用它像这样:

var newUser = new User({ 
    password: password, 
    field: value, 
    field: value, 
    field: value etc 
}); 
User.updateUser(newUser, userId, function(){ 
    // rest of your code 
}); 

你已经有了一个再这样可用的功能,无论何时都会更新用户您传递给它的字段数量。

另外,你的bcrypt的使用和我的实际上是一样的。即

bcrypt.hash(myPlaintextPassword, saltRounds, function(err, hash) { 

是一样的:

bcrypt.genSalt(saltRounds, function(err, salt) { 
    bcrypt.hash(myPlaintextPassword, salt, function(err, hash) { 

从自己的文件:https://www.npmjs.com/package/bcrypt