0

This is PUT method I want to hash my password(using passport) & and update it.

router.put('/reset/:token', function(req, res) {
    console.log('listening');
  User.findOneAndUpdate({resetPasswordToken:req.params.token},{
    password: req.body.password,
    resetPasswordToken: undefined,
    resetPasswordExpires: undefined
  },function(err,user) {
    if(err) {
      console.log(err + 'is here');
    } else {
      res.json(user);
    }
  });
    });

I want to hast the variable only password.How can I hash within this method & then update it.

1 Answers1

0

I'm assuming you are using Mongoose. First, create a pre method inside your Schema.

UserSchema

const mongoose            = require('mongoose')
    , bcrypt              = require('bcrypt-nodejs')
    , SALT_WORK_FACTOR    = 10;

 const UserSchema = new mongoose.Schema({
 ... // schema here
});

/**
 * Hash password with blowfish algorithm (bcrypt) before saving it in to the database
 */
UserSchema.pre('save', function(next) {
    var user = this;

    // only hash the password if it has been modified (or is new)
    if (!user.isModified('password'))
        return next();

    user.password = bcrypt.hashSync(user.password, bcrypt.genSaltSync(SALT_WORK_FACTOR), null);
    next();
});

mongoose.model('User', UserSchema);

And then in your route:

router.put('/reset/:token', function(req, res, next) {
    User.findOne({resetPasswordToken: new RegExp('^' + req.params.token + '$', "i")}, 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.save().then(function (user) {
            return res.status(200).json(user);
        });
    });
});
B_CooperA
  • 659
  • 1
  • 9
  • 28
  • yes, I have tried as you said but it 's not hashing the password. I have posted a new question in detail. Please once go through it. https://stackoverflow.com/questions/51380030/unable-hash-the-password-in-mean-stack –  Jul 17 '18 at 11:17