I have looked at the other answers to the question on here but still not getting anywhere. I cannot get the comparePassword function to return true
module.exports.createUser = function(newUser, callback) {
bcrypt.genSalt(10, function(err, salt){
bcrypt.hash(newUser.password, salt, function(err, hash){
newUser.password = salt;
newUser.save(callback);
});
});
};
module.exports.comparePassword = function(candidatePassword, hash, callback){
console.log("Provided password is " + candidatePassword);
console.log("Provided hash is " + hash);
bcrypt.compare(candidatePassword, hash, function(err, isMatch) {
if(err) throw err;
console.log(isMatch);
callback(null, isMatch);
});
}
So if we take the user in test at this stage you can see their data
{ _id: 5aec6f702a4a181f261a43fe,
full_name: 'Its me',
username: 'myusername',
email: 'myemail#gmail.com',
tel_number: '12345678',
password: '$2a$10$6GCgZDt.FL/eeZ1NsDASe.', // text version = test
__v: 0
}
When comparePassword is run the console logs return
Provided password is test
Provided hash is $2a$10$6GCgZDt.FL/eeZ1NsDASe.
So to me they match right?
Not sure what is going on here.
Could you try replacing the line newUser.password = salt; with newUser.password = hash; ?
And let us know if that works.
I have an example in my github repo, it might help
https://github.com/shirshendubhowmick/jwt-demo
Here is a snippet of the code from the repo
bcrypt.genSalt(10, (error, salt) => {
bcrypt.hash(user.password, salt, (error, hash) => {
user.password = hash;
next();
});
});
Related
Well, i have simple user edit in node,express,mongodb. But i am unable to hash password to bcrypt. In registration works everything allright but that was tutorial...
Here is part of my routes/users.js
Everything is updated but password is not hashed and i dont know what to do.
router.post("/profile", function (req, res) {
let user = {};
user.firstname = req.body.firstname;
user.lastname = req.body.lastname;
user.email = req.body.email;
user.password = req.body.password;
user.password2 = req.body.password2;
req.checkBody("firstname", "Firstname is required").notEmpty();
req.checkBody("lastname", "Lastname is required").notEmpty();
req.checkBody("email", "Email is required").notEmpty();
req.checkBody("email", "Email is not valid").isEmail();
req.checkBody("password", "Password is required").notEmpty();
req
.checkBody("password", "Password must be longer then 8 chars bitch")
.len(8, 64);
req
.checkBody("password2", "Passwords do not match")
.equals(req.body.password);
var errors = req.validationErrors();
if (errors) {
res.render("profile", {
errors: errors
});
} else {
bcrypt.genSalt(10, function(err, salt) {
bcrypt.hash(user.password, salt, function(err, hash) {
user.password = hash;
});
});
let query = {_id:req.user.id}
User.update(query, user, function(err){
if(err){
console.log(err);
return;
} else {
res.redirect('/');
}
});
}});
Here is my hasing for registration in models/users.js that i was inspired by.
module.exports.createUser = function(newUser, callback) {
bcrypt.genSalt(10, function(err, salt) {
bcrypt.hash(newUser.password, salt, function(err, hash) {
newUser.password = hash;
newUser.save(callback);
});
});
};
I will be thankfull for any help.
Well after hous its solved.
I just changed it to.
bcrypt.genSalt(10, function(err, salt) {
bcrypt.hash(user.password, salt, function(err, hash) {
user.password = hash;
let query = {_id:req.user.id}
User.update(query, user, function(err){
if(err){
console.log(err);
return;
} else {
res.redirect('/');
}
});
});
});
}});
I'm very new to Nodejs / Mongo (with Mongoose). I'm using the bcrypt module to hash the password from a HTML form. In my db.create function, I'm not able to store the variable storehash in mongodb.
I don't get any errors but its just blank in the database. I have crossed check every other line of the code and it seems to be working. I don't understand why I'm not able to store a variable as "password: storehash" whereas I'm allowed to store something like "password: 'test' "
I'm sure I'm making some noob mistake somewhere. I'd appreciate any help!
var db = require('../models/users.js');
var bcrypt = require('bcryptjs');
module.exports.createuser = function(req,res){
var pass = req.body.password;
var storehash;
//passsord hashing
bcrypt.genSalt(10, function(err,salt){
if (err){
return console.log('error in hashing the password');
}
bcrypt.hash(pass, salt, function(err,hash){
if (err){
return console.log('error in hashing #2');
} else {
console.log('hash of the password is ' + hash);
console.log(pass);
storehash = hash;
console.log(storehash);
}
});
});
db.create({
email: req.body.email,
username: req.body.username,
password: storehash,
}, function(err, User){
if (err){
console.log('error in creating user with authentication');
} else {
console.log('user created with authentication');
console.log(User);
}
}); //db.create
};// createuser function
Your db.create should go right below console.log(storehash);, not after the bcrypt.salt.
When you put it after bcrypt.salt, what you do is: while you're generating salt for your password and then hashing the salted password, you're also storing stuff in your database using db.create. They are executed simultaneously, not sequentially. That's why, while you're hashing your password, you're also creating a user with db.create without a password.
In other words, it should be:
bcrypt.genSalt(10, function(err,salt){
if (err){
return console.log('error in hashing the password');
}
bcrypt.hash(pass, salt, function(err,hash){
if (err){
return console.log('error in hashing #2');
} else {
console.log('hash of the password is ' + hash);
console.log(pass);
storehash = hash;
console.log(storehash);
db.create({
email: req.body.email,
username: req.body.username,
password: storehash,
}, function(err, User){
if (err){
console.log('error in creating user with authentication');
} else {
console.log('user created with authentication');
console.log(User);
}
}); //db.create
}
});
});
I'm struggling to prevent updating user's password in database if the password input was left empty.
Here is the route responsible for updating user data:
router.put('/update', passport.authenticate('jwt', {session: false}), (req, res) => {
let user = req.user;
user.firstname = req.body.firstname;
user.lastname = req.body.lastname;
user.username = req.body.username;
user.email = req.body.email;
user.password = req.body.password || null;
User.updateUser(user, (err) => {
if (err) {
res.json({
success: false,
message: 'User details couldn\'t be updated.'
});
} else {
res.json({
success: true,
message: 'User updated'
});
}
});
});
And here is the User model method which generates a hash of a password and saves the new data in the database:
module.exports.updateUser = function (user, callback) {
if (user.password) {
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(user.password, salt, (err, hash) => {
if (err) throw err;
user.password = hash;
});
});
}
user.save(callback);
};
I check if the password value was given but I don't know how to keep the old encrypted password in the database if there is no new value given for the password. If user doesn't fill the password input, it is being saved as null, as expected though...
I hope there is an approach to achieve this, I just can't figure out at the moment as I'm a beginner.
Thank you in advance!
I guess that you are using Mongoose to communicate with the Database.
Change this Line of your code :
user.password = req.body.password || null;
with this :
if(req.body.password != null) {
user.password = req.body.password
}else{
/* find each user with a last name matching 'user.userame', selecting
/*the `password` field and returning the result in 'usr'
*/
User.find({'username' : user.username}, 'password', function (err, usr) {
if (err) return handleError(err);
user.password = usr.password;
})
}
Based on #Neil Lunn's suggestion about checking the documentation, I came up with a solution. I changed the updateUser method to this:
module.exports.updateUser = function (user, callback) {
if (user.password) {
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(user.password, salt, (err, hash) => {
if (err) throw err;
user.password = hash;
user.save(callback);
});
});
} else {
User.findById(user.id).update({
username: user.username,
email: user.email,
firstname: user.firstname,
lastname: user.lastname
}, callback);
}
};
If the password is present, then update everything as is, if no password provided, then update only the needed fields except the password.
Maybe this is not the best solution, but it works for now.
Thank you!
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! :)
Found out what was wrong!
module.exports.changePassword = function(user, newPassword, callback){
var query = {username: user.username};
bcrypt.genSalt(10, function(err, salt){
// it has to be newPassword instead of user.password
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);
});
}
});
}
});
});
};
// CORRECT ONE
module.exports.changePassword = function(user, newPassword, callback){
var query = {username: user.username};
bcrypt.genSalt(10, function(err, salt){
bcrypt.hash(newPassword, 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);
});
}
});
}
});
});
};
For some reason the code below does not save to the database? Can anyone tell me why this will not work to save a user's new password using PassportJS?
UserSchema.pre('save', function(next) {
var user = this;
var SALT_FACTOR = 5;
if (!user.isModified('password')) return next();
bcrypt.genSalt(SALT_FACTOR, function(err, salt) {
if (err) return next(err);
bcrypt.hash(user.password, salt, null, function(err, hash) {
if (err) return next(err);
user.password = hash;
next();
});
});
});