I have a MEAN application that is trying to implement a GET Request for '/changepassword'. This file is located in '/users/changepassword'. I am using Mongoose and bcryptjs for my password hashing. Please take a look at my code below.
This is /users/changepassword
// Change Password
router.post('/changepassword', function(req, res){
var username = req.body.username;
var password = req.body.oldPassword;
var newPassword = req.body.newPassword;
User.getUserByUserName(username, function(err, user){
if(err) throw err;
if(user === null){
res.json({success: false, msg: "The given username does not exist."});
}else{
User.comparePassword(password, user.password, function(err, isMatch){
if(err) throw err;
if(isMatch)
{
User.changePassword(user, newPassword,function(err, changedPassword){
if(err) throw err;
else{
if(changedPassword === true){
res.json({success: true, msg: "Your password has been changed."});
}
else {
res.json({success: false, msg: "Your password was unable to be changed."});
}
}
});
}
});
}
});
});
This is the Mongoose changepassword function located in /models/user
module.exports.changePassword = function(user, newPassword, callback){
var query = {username: user.username};
bcrypt.genSalt(10, function(err, salt){
bcrypt.hash(user.password, salt, function(err, hash){
if (err) throw err;
else{
user.password = hash;
User.findOneAndUpdate(query, { $set: { password: user.password }}, {new: true}, function(err, newUser){
if(err) throw err;
else{
bcrypt.compare(newPassword, newUser.password, function(err, isMatch){
if(err) throw err;
console.log(isMatch);
callback(null, isMatch);
});
}
});
}
});
});
};
Here are all other functions used in the /models/user
module.exports.getUserByUserName = function(username, callback){
var query = {username: username};
User.findOne(query, callback);
};
module.exports.comparePassword = function(candidatePassword, hash, callback){
bcrypt.compare(candidatePassword, hash, function(err, isMatch){
if(err) throw err;
callback(null, isMatch);
});
};
When I use postman, this is the output I receive
{
"success": false,
"msg": "Your password was unable to be changed."
}
Any help is much appreciated! :)
via A. Angee
No comments:
Post a Comment