I have a basic mongoose authentication, with bcryptjs to hash passwords. Both bcrypt and mongoose return promises. In my routes.js I have the following script which gets stuck after finding the User in the db:
routes.post('/auth', (req, res)=> {
User.findOne({'local.username': req.body.username})
.then(
user=> Promise.all([user, user.validate(req.body.password)])
)
.then(
results => {
console.log(results);
res.json({token: jwt.sign({id: results[0]._id}, config.secret)});
}
)
.catch(
err=> console.log(err)
);
});
As you can see I find the user, and then try to call its validate method (which gets called), but it won't resolve the promise nor throw an error. In my user.js which defines my UserSchema I have this code to compare passwords:
UserSchema.methods.validate = function (password) {
return bcrypt.compare(password, this.local.password);
};
This is called, but the returned promise seems like it vanishes, it is not resolved, the results variable is never logged.
One more thing, if I edit user validation code to this:
UserSchema.methods.validate = function (password) {
return bcrypt.compare(password, this.local.password).then(
results => {
console.log(results)
}
)
};
I get true logged to console, so it must be working but I don't want to resolve my promise here, I want to attach the .then(...) in my router, isn't it possible?
What am I doing wrong?
UPDATE:
If I put the compare method in the routes.js it works, but that is not what I want to do, I want to keep it in the user.js, but I thought this might point out the problem which I still cannot see. I guess I have to call then() immediately on the promise, but I don't see why.
User.findOne({'local.username': req.body.username})
.then(
user=> Promise.all([user, bcrypt.compare(req.body.password,user.local.password)])
)
.then(
results => {
console.log(results);
res.json({token: jwt.sign({id: results[0]._id}, config.secret)});
}
)
.catch(
err=> console.log(err)
);