Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
269 views
in Technique[技术] by (71.8m points)

mongodb - unable hash the password in mean stack

This is the code from routes file.

router.put('/reset/:token', function(req, res, next) {
  console.log('reseting the password');
  User.findOne({resetPasswordToken:req.params.token}, function(err, user) {
    if(err) {
      return next(err);
    }
    if (!user) {
      return res.status(422).json({errors: [{msg: 'invalid reset token'}]});
    }

    user.resetPasswordToken ='';
    user.resetPasswordExpires = '';
    user.password = req.body.password;
    User.addUser(user, (err, user) => {
      if(err){
        res.json({success: false, msg:'password has not changed'});
      } else {
        res.json({success: true, msg:'password has changed'});
      }
    });
  });
});

This part of the code is from my schema file.

const UserSchema = mongoose.Schema({
  password: {
    type: String,
    required: true
  },

  resetPasswordToken: {
    type: String
  },
  resetPasswordExpires: {
    type: Date
  }

});

  const User = module.exports = mongoose.model('User', UserSchema);
module.exports.addUser = function(newUser, callback){
    bcrypt.genSalt(10, (err, salt) => {
      bcrypt.hash(newUser.password, salt, (err, hash) => {
        if(err) throw err;
        newUser.password = hash;
        newUser.save(callback);
      });
    });
  }

When I try to rest the password it is storing as I've given the input. It is not hashing the password. For example, I have given the password as "zp12345", in the database it is storing as "password" : "zp12345".

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For solve the problem you need to fix your addUser method:

var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');

module.exports.addUser = function(newUser, callback){
    bcrypt.hash(newUser.password, bcrypt.genSaltSync(10), null, (err, hash) => {
       if (err) {
         return next(err);
       }
       newUser.password = hash;
       newUser.save(callback);
    })
};

Here there is another example: Mongoose Pre Save Changing Password

And this is the library documentation: Bcrypt Nodejs


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...