Reputation: 711
Here I'm learning MongoDB with Node.js Express App. I'm securing my passwords with Bcrypt. Encryption and saving in mongodb is successful, but when I try to compare passwords for SigIn, it just fails.
SignUp route
router.post('/signUp', (req, res, next) => {
let userData = req.body;
mongoose.connect(DB_URL, {useNewUrlParser: true}, (err) => {
if (err) throw err;
console.log('DB is connected Successfully');
bcrypt.hash(userData.password, saltRounds, function (err, hash) {
User.create({
name: userData.name,
fname:userData.fname,
email:userData.email,
password:hash
}).then(() => {
//success callback
res.send('Saved');
}).catch(next);
});
});
});
SignIn route
router.post('/signIn', (req, res) => {
const incomingEmail = req.body.email;
const incomingPassword = req.body.password;
mongoose.connect(DB_URL, {useNewUrlParser: true}, (err) => {
if (err) throw err;
console.log('DB is connected Successfully');
User.find({incomingEmail}).then((user) => {
if (user.length > 0) {
bcrypt.compare(incomingPassword, user.password).then(function (result) {
res.status(200).json({status: 200, data: user[0]});
}).catch(() => {
res.send('incorrect password')
});
} else {
res.status(404).json({status: 404, data: 'User not found'});
}
}).catch(() => {
res.status(404).json({status: 404, data: 'Email not matched'});
});
});
});
With valid credentials for signin it shows
{"status": 404, "data": "User not found" }
Even I try to send only password if email is matched, still it returns nothing.
User.find({incomingEmail}).then((user) => {
res.send(user.password);
}).catch(() => {
res.status(404).json({status: 404, data: 'Email not matched'});
});
I'm using WebStorm on Windows 10.
node version is 11.12.0
Project package.json
"dependencies": {
"bcrypt": "3.0.4",
"body-parser": "latest",
"cookie-parser": "~1.4.3",
"debug": "~2.6.9",
"express": "~4.16.0",
"mongodb": "^3.1.13",
"mongoose": "^5.4.17",
"mongoose-unique-validator": "^2.0.2",
"morgan": "~1.9.0"
}
If anyone have answer let me know. Thanks
Upvotes: 3
Views: 894
Reputation: 3295
There is nothing wrong with your code. I have tested it on my side here. The only anomaly I am looking at is while sending the response you are having an Array of Responses but reading it as a single object.
Here is what the above jargon I said means
INSTEAD OF
User.find({incomingEmail}).then((user) => {
res.send(user.password);
}).catch(() => {
res.status(404).json({status: 404, data: 'Email not matched'});
});
Do this
User.find({incomingEmail}).then((user) => {
res.send(user[0].password);
}).catch(() => {
res.status(404).json({status: 404, data: 'Email not matched'});
});
OR IN ANOTHER CASE
what I can see you can do is to instead of using MONGOOSE ONLY FIND method ! you can go with FINDONE method too so that it would have no need to read out an array of JSON responses for a single user. FINDONE will help you with the code you already have.
Upvotes: 1