Skip to content

Handling expired token#1

Open
NotReal003 wants to merge 3 commits intonotunderctrl:mainfrom
NotReal003:main
Open

Handling expired token#1
NotReal003 wants to merge 3 commits intonotunderctrl:mainfrom
NotReal003:main

Conversation

@NotReal003
Copy link

@NotReal003 NotReal003 commented Nov 18, 2024

Make sure to update Middleware accordingly

Copy link

@The-LukeZ The-LukeZ left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, however the changes in the auth route could be improved by separating things into a distinct function.

Improved code:

const clearTokenCookie = (res) => {
  res.clearCookie('token', { httpOnly: true, secure: true });
};

const verifyTokenMiddleware = async (req, res, next) => {
  const token = req.cookies.token;

  if (!token) {
    clearTokenCookie(res);
    return res.status(200).json({ message: 'Successfully logged out. No active session found.' });
  }

  try {
    const savedToken = await Blacklist.findOne({ blacklistToken: token });

    if (savedToken) {
      clearTokenCookie(res);
      return res.status(200).json({ message: 'Successfully logged out. Active session already blocked.' });
    }

    req.decodedToken = jwt.verify(token, process.env.JWT_SECRET);
    next();
  } catch (err) {
    clearTokenCookie(res);
    return res.status(200).json({ message: 'Successfully logged out. Invalid or expired session token.' });
  }
};

router.get('/signout', verifyTokenMiddleware, async (req, res) => {
  try {
    await Blacklist.create({ blacklistToken: req.cookies.token, user_id: req.decodedToken.id });
    clearTokenCookie(res);
    res.status(200).json({ message: 'Successfully logged out.' });
  } catch (err) {
    clearTokenCookie(res);
    res.status(500).json({ message: 'Error during logout. Please try again later.' });
  }
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants