I quite a beginner and used a tutorial for authentication. I am using jwt and based on that tutorial I have added a middleware. I dont know/think its right:
- Since im using jwt, I am validating the token in my middleware, all correct. However Im also taking the userid from payload, making a request to the db and if i find a user, i put it on req.user. Am I not failing the whole point of using jwt then? Is not the point in using jwt to not make every time a request to the db?
- This is not related to using jwt, but in case my middleware is fine, when there is no db connection, at the point where Im fetching user from db, I get an err which makes sense, but somehow the error is not not handled, even though I do have a catch. Am I doing it wrong? Thank you!
module.exports = (req, res, next) => {
const { authorization } = req.headers;
try {
if (!authorization) return res.status(401).send({error: 'you must be logged in'})
const token = authorization.replace('Bearer ', "");
jwt.verify(token, 'MY_SECRET_KEY', async (err, payload) => {
if (err) return res.status(401).send({error: 'you must be logged in'})
const {userId} = payload;
const user = await User.findById(userId);
if (user) req.user = user;
else return res.status(401).send({error: 'you must be logged in'})
next();
})
} catch (err) {
res.status(400).send("too bad its an err")
}
};