Reputation: 865
I'm trying to build authentication using nodejs with jwt and I successfully finish the register process to register new users to mongo database but I have problem with the login and this is the login code:
// Login
router.post('/log', (req, res) => {
User.findOne({ email: req.body.email }, { password: req.body.pass })
.exec()
.then(function(user) {
bcrypt.compare(req.body.pass, user.pass, (err, result) => {
if (err) {
return res.status(401).send('error');
}
if (result) {
const token = jwt.sign({
email: user.email,
_id: user._id
},
'secret',
{
expiresIn: '1h'
});
return res.status(200).json({
success: 'jwt',
token: token
});
}
return res.status(401).send('error happen');
});
})
.catch(err => {
res.status(401).send(err);
});
});
when I type in postman /log and in the body type this structured:
{
"email": "[email protected]",
"password": "12345",
}
I get this message as response in postman:
error happen
I can't understand what's the error with code while the register worked well ?
Upvotes: 1
Views: 316
Reputation: 1102
Your error is not with JWT, the problem is that bcrypt.compare()
returned false then that is why your method does not enter the if and pass to the return with your error message.
Based on your code I can propose this:
You have to be sure that you are storing your hash password in the database or the process you are doing is fine but the password you enter is incorrect.
In your search method you use the plain text password as a parameter to find the user, in this case the password does not have to be stored in an insecure way that is why a password hash is used so you should remove that search parameter and find the user to compare passwords.
User.findOne({ email: req.body.email })
Upvotes: 1
Reputation: 453
When you call the User.findone function, it tries to find the user with given email and unhashed password.
Change this line
User.findOne({ email: req.body.email }, { password: req.body.pass })
with this:
User.findOne({ email: req.body.email })
Therefore you will be able to get the user and can compare the hashed passwords
Upvotes: 2