Bcrypt returns false on login - mongodb

I know this question has been asked many times but I cannot find an answer to my problem both here or on github. I have a login handler which compares hashed password from db to the the one typed by the user on login. bcrypt.compare almost always returns false. I say almost because sometimes it just starts working and it always works after I register user. I am trying to find what is wrong with my code but cant figure it out. Any help is highly appreciated.
mongoose pre save
userModel.schema.pre('save', function(next) {
let user = this;
bcrypt.hash(user.password, 10, null)
.then(hash => {
console.log(hash)
user.password = hash;
user.confirmPassword = hash;
next();
})
.catch(err => res.sendStatus(404));
});
login handler
exports.loginUser = (req, res) => {
let user = new User.model(req.body);
User.model
.find({email: user.email})
.exec()
.then(users => {
if (!users.length) {
res.status(401).json({
message: "Auth failed - user does not exist"
});
} else {
bcrypt
.compare(req.body.password, users[0].password)
.then(result=> {
console.log(user.password, users[0].password)
console.log(bcrypt.hashSync(req.body.password, 10))
if (result) {
const token =
jwt
.sign({ email: users[0].email, id: users[0]._id },
'secretKey', { expiresIn: "1h"});
res.status(200).json({
message: "Auth success - logged in",
token,
users
});
} else {
res.json('not working');
}
})
.catch(err => res.status(401).json({message: "Auth failed"}));
}
});
};
register handler
exports.registerUser = (req, res) => {
let user = new User.model(req.body);
if(user.email) {
User.model
.find({email: user.email})
.exec()
.then(docs => {
if (!docs.length) {
if (user.password !== user.confirmPassword) {
return res.status(404).json('passwords do not match');
}
user.save(function (err, user) {
if (err) return (err);
});
console.log('user saved');
res.sendStatus(200);
} else {
res.status(404).json('user exists');
}
})
.catch(err => res.sendStatus(404).json(res.body));
} else {
res.status(404).json('user name required');
}
};

The problem might be that you generate a new password each time the user is saved. You should skip this though.
userModel.schema.pre('save', function(next) {
let user = this;
if(!user.isModified("password")) return next();
bcrypt.hash(user.password, 10, null)
.then(hash => {
console.log(hash)
user.password = hash;
user.confirmPassword = hash;
next();
})
.catch(err => res.sendStatus(404));
});
Just a shot in the dark though. under the assumption something got changed and this was called again, because you stated it is working sometimes.

Related

Store collection value to variable

I am having issues storing a value in mongodb to a variable to use within my webpage.
When the user fills out a form on my website, I am trying to figure out what the arrivalTrailer was when the user filled out the arrival form.
So far I have
function previousLoad(loadNumber, callback){
CheckCall.find({loadNumber: loadNumber}).sort({date: 'desc'}).limit(1), function(err, arrival){
if (err){
callback(err, null);
}
else {
callback(null, arrival[0]);
}
}};
previousLoad(loadNumber, function(err, arrival){
if (err){
console.log(err);
}
else{
arrivalTrailer = arrival;
console.log(arrival);
}
});
console.log(previousLoad.arrival);
console.log(arrivalTrailer);
Both output as undefined when I try to console.log the variables.
Thank you :D
Try this :
async function previousLoad(loadNumber) {
try {
let resp = await CheckCall.find({ loadNumber: loadNumber }).sort({ date: -1 }).limit(1)
return resp[0]
} catch (error) {
console.log('error ::', error)
throw new Error (error)
}
}
/** You can return response from previousLoad but to test it, Call it from here */
previousLoad(loadNumber).then(resp => { console.log('successfully found ::', resp)}).catch(err => { console.log('Error in DB Op ::', err)});

How do you validate password using mongoose for mongoDB in an express app for logging in a user?

I am trying to have a user log in by their email and password. MongoDb docs shows hashing the password with bcrypt in the user model. It also provides a nice way to validate the password in the model as well. My problem is how to I use that validation from the "controller"? I am very aware "if (req.body.password === user.password)" will not work because one is hashed and the other is not.
I have been searching for answers for hours and can't seem to find that connection on how I use that "UserSchema.methods.comparePassword" method in my post request to log in. This isn't completely a real log in, just trying to get the password to validate and send back a key once logged in. Here are the docs: https://www.mongodb.com/blog/post/password-authentication-with-mongoose-part-1
// This is my UserModel
let mongoose = require('mongoose'),
Schema = mongoose.Schema,
bcrypt = require('bcrypt'),
SALT_WORK_FACTOR = 10
var hat = require('hat');
let UserSchema = new Schema({
email: {
type: String,
required: true,
index: {
unique: true
}
},
password: {
type: String,
require: true
},
api_key: {
type: String
}
});
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();
// generate a salt
bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
if (err) return next(err);
// hash the password using our new salt
bcrypt.hash(user.password, salt, function(err, hash) {
if (err) return next(err);
// override the cleartext password with the hashed one
user.password = hash;
user.api_key = hat();
next();
});
});
});
UserSchema.methods.comparePassword = function(candidatePassword, cb) {
bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {
if (err) return cb(err);
cb(null, isMatch);
});
};
module.exports = mongoose.model('user', UserSchema);
// This is the sessions.js
let UserModel = require('../../../models/user.model');
var express = require('express');
var router = express.Router();
router.post('/', (req, res, next) => {
UserModel.findOne(
{
$or: [
{ email : req.body.email }
]
}
)
.then(user => {
if (req.body.password === user.password) {
res.setHeader("Content-Type", "application/json");
res.status(200).send(JSON.stringify({
"api_key": `${user.api_key}`
}));
} else {
res.status(404).send("Incorrect email or password")
}
})
.catch(error => {
res.setHeader("Content-Type", "application/json");
res.status(500).send({error})
})
})
module.exports = router
If I just find user by email, everything works fine. Just need to figure out how to use the compare password method in the user model. Thanks!
Maybe have something like this in your model:
User = require('./user-model');
.......
User.findOne({ username: 'jmar777' }, function(err, user) {
if (err) throw err;
user.comparePassword('Password123', function(err, isMatch) {
if (err) throw err;
console.log('Password123:', isMatch); // -> Password123: true
});
........
Other resources:
http://devsmash.com/blog/password-authentication-with-mongoose-and-bcrypt
https://www.abeautifulsite.net/hashing-passwords-with-nodejs-and-bcrypt
https://medium.com/#mridu.sh92/a-quick-guide-for-authentication-using-bcrypt-on-express-nodejs-1d8791bb418f
Hope it helps!

Mongoose: findOneAndUpdate pre hook not working

I've searched about this issue and all the solutions that I've found didn't actually work. I'm currently using this function to encrypt the password before storing in the database but even though the values are being changed when logging this, the password isn't stored like it was changed in the function.
UserSchema.pre('findOneAndUpdate', function(next) {
const update = this.getUpdate();
if (!_.isEmpty(update.password)) {
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(update.password, salt, (err, hash) => {
this.getUpdate().password = hash;
next();
})
})
}
next();
});
I've also tried to change the value of this._update.password instead but it didn't work either. I've also tried using $set or even using a post hook but none of them helped either. What am I doing wrong?
I just tested this locally with:
var result = Author.findOneAndUpdate({ _id: <some id> }, { password: '111' }).exec()
and this pre hook:
AuthorSchema.pre('findOneAndUpdate', function(next) {
this._update.password = 'BBB'
next();
});
Password was saved as BBB
Author schema has a password field which is type: String
I am on 3.6.5
In your bcrypt case you have also an extra next() without else which is messing you up ... should be:
UserSchema.pre('findOneAndUpdate', function(next) {
const update = this.getUpdate();
if (!_.isEmpty(update.password)) {
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(update.password, salt, (err, hash) => {
this.getUpdate().password = hash;
next();
})
})
} else {
next();
}
});
user.pre('findOneAndUpdate', function(next){
const user=this.getUpdate().$set;
if(!user.password){
next();
}
else{
bcrypt.genSalt(10, 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();
});
});
}
})

unread flag is not being updated with Mongoose

I have a conversations collection in my database, and I'm using Mongoose to update the unread flag of a single document.
This is my code:
router.post('/reply/:conversation_id', ensureAuthenticated, (req, res, next) => {
Conversation.findById(req.params.conversation_id, (err, conversation) => {
// If the user that's logged in was the one who created the conversation, and is submitting a reply, run this code
if (req.user._id == conversation.created_by_user_id) {
User.findById(conversation.sent_to_user_id, (err, user) => {
Message.create({
//...
}, (err, message) => {
if (err) {
console.log(err)
} else {
message.conversations.push(conversation._id)
conversation.unread = true
conversation.save() // This is being saved to the database
message.save()
res.redirect('/conversations/' + conversation._id)
}
})
})
} else {
// Otherwise, if the user that's logged in was *not* the one who created the conversation, and is submitting a reply, run this code
User.findById(conversation.created_by_user_id, (err, user) => {
Message.create({
//...
}, (err, message) => {
if (err) {
console.log(err)
} else {
message.conversations.push(conversation._id)
conversation.unread = true
conversation.save() // This is not being saved
message.save()
res.redirect('/conversations/' + conversation._id)
}
})
})
}
})
});
The if part saves conversation.unread = true to the db. The else part does not.
Both parts of the conditional essentially do the same thing (save the conversation's unread flag as true, and save the message), but only the first part of the conditional works when setting unread to true.
Can someone please help me figure out why the unread flag is not being saved as true in the else statement?
You're trying to call save synchronously.
.save takes a callback. It is asynchronous.
See my version below.
router.post('/reply/:conversation_id', ensureAuthenticated, (req, res, next) => {
Conversation.findById(req.params.conversation_id, (err, conversation) => {
// If the user that's logged in was the one who created the conversation, and is submitting a reply, run this code
if (req.user._id == conversation.created_by_user_id) {
User.findById(conversation.sent_to_user_id, (err, user) => {
Message.create({
//...
}, (err, message) => {
if (err) {
console.log(err)
} else {
message.conversations.push(conversation._id)
conversation.unread = true
conversation.save() // This is being saved to the database
message.save()
res.redirect('/conversations/' + conversation._id)
}
})
})
} else {
// Otherwise, if the user that's logged in was *not* the one who created the conversation, and is submitting a reply, run this code
User.findById(conversation.created_by_user_id, (err, user) => {
Message.create({
//...
}, (err, message) => {
if (err) {
console.log(err)
//return here
return res.redirect('/error'); //
} else {
message.conversations.push(conversation._id)
conversation.unread = true
//.save takes a function callback
conversation.save((err) => {
//.save takes a function callback
message.save((err) => {
res.redirect('/conversations/' + conversation._id)
})
})
}
})
})
}
})
});

Understanding session in sailsJs with Passport

I have had many problems, when I want to get information from user model. I read some solutions, but I didnt understand.
This is my code:
* AuthController
var passport = require('passport');
module.exports = {
_config: {
actions: false,
shortcuts: false,
rest: false
},
login: function(req, res) {
passport.authenticate('local', function(err, user, info) {
if ((err) || (!user)) {
return res.send({
message: info.message,
user: user
});
}
req.logIn(user, function(err) {
if (err) res.send(err);
return res.send({
message: info.message,
user: user
});
});
})(req, res);
},
logout: function(req, res) {
req.logout();
res.redirect('/');
},
signup: function (req, res) {
var data = req.allParams();
User.create({email:data.email,password:data.password,name:data.name}).exec(function(error,user){
if(error) return res.negotiate(err);
if(!user)return res.negotiate(err);
return res.ok();
});
}
};
*view
<h1>List of my dates</h1>
<h1><%= email %></h1>
<h1><%= req.user.name %></h1>
*model
attributes: {
email: {
type: 'email',
required: true,
unique: true
},
password: {
type: 'string',
minLength: 6,
required: true
},
toJSON: function() {
var obj = this.toObject();
delete obj.password;
return obj;
}
},
beforeCreate: function(user, cb) {
bcrypt.genSalt(10, function(err, salt) {
bcrypt.hash(user.password, salt, function(err, hash) {
if (err) {
console.log(err);
cb(err);
} else {
user.password = hash;
cb();
}
});
});
}
};
Only works if I use res.render('view', {email: req.user.email}) but, I would like to use the user data in many views. I cant write methods with Current user params, becouse dont work.
Thanks.
It is unclear to me what your actual problem is or what the question actually is but I will try to help.
Look here:
login: function(req, res) {
passport.authenticate('local', function(err, user, info) {
if ((err) || (!user)) {
return res.send({
message: info.message,
user: user
});
}
...
})(req, res);
},
There you are adding data (locals) to the ejs and the values are message and user so in the ejs you must reference it as this, so you will use user.name and not req.user.name? I'm not sure why you're binding the (req, res) either.
It's confusing because your ejs uses the email value but I don't see it there as a local so maybe thats your problem, it must be defined?
Consider the following simple example:
// User Controller
// GET request /signin
// The signin form
signin(req, res) {
// Load the view from app/views/*
return res.view('signin', {
title: 'Sign In'
});
},
// POST request to /signin
// This was posted from the signin form
// Use io.socket.post(...) to do this from the signin form
// Can use window.location.replace('/account') on successful request
authenticate(req, res) {
// The data posted, email and password attempt
var data = req.allParams();
// Does it match?
User.findOne({
email: data.email,
// This is stupid, don't ever use plain text passwords
password: data.password
})
.exec(function(err, user) {
// Server related error?
if (err) res.serverError(err.message);
// No user was found
if (!user) res.badRequest('Username or password not found');
// Sign the user in
req.session.userId = user.id;
// User was found
res.ok();
});
},
// GET request to /account
// Displays the users information
// Can use policies to ensure that only an authenticated user may access their own account information
account(req, res) {
// If the user is not signed in
// This is an alternative to using the sails policy isLoggedIn
if (!req.session.userId) res.redirect('/signin');
// Get the users details
User.findOne({
id: req.session.userId
})
.exec(function(err, user) {
// Server related error?
if (err) res.serverError(err.message);
// No user was found
if (!user) res.redirect('/signin');
// Load the ejs file that displays the users information
return res.view('account/index', {
title: 'Account Information',
user: user
});
});
},
// Account View
<p>Email: {{user.email}}</p>
<p>Password: {{user.password}}</p>
Check this out if you want to deal with password encryption: http://node-machine.org/machinepack-passwords
And this if you want to deal with the strength tests (when the user sets the password): https://www.npmjs.com/package/owasp-password-strength-test
This is as passport seems overkill if you're only doing local authentication?