4
\$\begingroup\$

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) {
      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?

\$\endgroup\$

0

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.