2017-03-09 108 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