I'm using Sequelize and Google oAuth for authentication, I want to create a middleware that
- Verifies the sent token passed in the headers matches the one the user was initially signed to.
- Finds the user if he/she exists and returns it to the client.
The middleware be used for protected routes.
const getCurrentUser = (req, res, next) => {
if (!req.headers || !req.headers.authorization) return res.status(401).end();
const token = req.headers.authorization.split(' ')[1];
if (!token) return res.status(401).end();
JWT.verify(token, process.env.JWT_SECRET, async (err, decoded) => {
if (err) {
res.status(401).end();
} else {
res.locals.JWT = decoded;
const user = await models.user.findOne({ where: { id: decoded.id } });
if (!user) return res.status(404).send({ message: 'No user found' });
req.user = user;
next();
}
});
};
One thing I'd like to make sure I'm doing correctly is error handling. Does this look alright? Anything to change/improve on?