I'm using Sequelize and Google oAuth for authentication, I want to create a middleware that

  1. Verifies the sent token passed in the headers matches the one the user was initially signed to.
  2. 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) {
    } 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;

One thing I'd like to make sure I'm doing correctly is error handling. Does this look alright? Anything to change/improve on?


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.