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('/');
}
});
});
});
}});
Related
I need help with my codes. I have successfully sent the hashed password to the database, but the login/authentication part where the "compare" is done isn't working. Its mostly saying password is undefined.
Here is the logic.
const salt = bcrypt.genSaltSync(10);
let tohash;
function hashPass(password) {
tohash = bcrypt.hashSync(password, salt, function (err, hash) {
if (err) return err;
user.password = hash;
});
console.log('Password is ' + password);
console.log('Tohash is ' + tohash);
return { tohash: tohash };
}
function correctpass(password, user) {
console.log('Tohash here is ' + tohash);
let deHash = bcrypt.compare(password, user.password, function (err, result) {
console.log('Password is ' + password);
if (err) {
console.log('Incorrect password');
}
console.log('Correct Password');
return result;
});
return { deHash: deHash };
}
export { hashPass };
export { correctpass };
Here is where the invocation is done using Sequelize
const unHash = correctpass(password);
try {
user.findOne({
where: {
id : 55,
email: "preciousegunjobi05#yahoo.com",
//password: isPasswordCorrect.password.toString(),
password: unHash.deHash(req.body.password),
user_type: "tutor"
}
}).then(userdetails => {
res.send(userdetails);
console.log("data is " + userdetails);
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();
});
});
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!
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();
});
});
});
I have a form where users can create a room with an optional password field. I want to save the password only if the password field contains something ( is not empty). I have hash middleware that hash the password before saving it to mongodb. Even if the password field is empty it is saving a hash value. I tried to add a condition to check if there is a value only then to proceed with the hashing but this does not seem to work.
Here is my post :
exports.postCreateRooms = function(req, res, next) {
req.assert('workspace', 'Please enter a board name').notEmpty();
var errors = req.validationErrors();
var enableVideo;
if (errors) {
req.flash('errors', errors);
return res.redirect('/dashboard');
}
var url = uuid.v4();
var room = new Room({
roomUrl: url,
roomName: req.body.workspace,
owner:req.user._id,
ownerEmail:req.user.email,
dateCreated: Date(),
lastUpdated: Date(),
users: [req.user._id]
});
if (req.body.password != ''){
room.password = req.body.password;
}
room.save(function(err) {
if (err) {
return next(err);
}
res.redirect('/board='+room.roomUrl);
});
};
here is my hash middleware :
roomSchema.pre('save', function(next) {
var room = this;
if(room.password){
bcrypt.genSalt(10, function(err, salt) {
if (err) {
return next(err);
}
bcrypt.hash(room.password, salt, null, function(err, hash) {
if (err) {
return next(err);
}
room.password = hash;
next();
});
});
}
});
What happens when you have the check in place?
From what I can see, you need a next() call outside of your if block in the middleware, so it knows to proceed even if there isn't a password specified.
It would look like
roomSchema.pre('save', function(next) {
var room = this;
if(room.password){
return bcrypt.genSalt(10, function(err, salt) {
if (err) {
return next(err);
}
bcrypt.hash(room.password, salt, null, function(err, hash) {
if (err) {
return next(err);
}
room.password = hash;
next();
});
});
}
next();
});