I use a passport to protect my API. Iโm kind of struggling to understand how I should send back a custom message in case of an error, and I hope to find an answer here.
Here is what I did:
Route (server.js):
router.route('/Applications').get(authController.BearerAuthenticated, applicationController.getApplications);
My Passport Stuff (authController.js):
Passport.use(new BearerStrategy(function(token, cb) { Token.findOne({token: token}, function(err, token){ if (err){return cb(null, false);} if (!token) { return cb(null, false); } return cb(null, token); }); })); exports.BearerAuthenticated = Passport.authenticate('bearer', {session: false});
My application method (Application.js)
exports.getApplications = function(req, res) { Application.find({userId:req.user._id}, function(err, apps) { if (err) res.send(err); res.json(apps); }); };
If my token is valid and the Bearer method returns
return cb(null, token);
Then I can introduce the getApplications method. It makes sense.
The fact is that the token is invalid, I donโt enter the method (it makes sense too), but I canโt understand how to return the user message to the client instead of the next message that I get by default.
Unauthorized
How can I return Json with an error code so that it correctly informs the user that his token is dead or simply does not exist?
Thank you for your time.:)