Hello Dev Community! 👋
It is Day 182 of my full-stack engineering path! Today, I focused on implementing session-based logout mechanisms in Express.js: Single-Device Logout and Logout From All Devices! 🔐⚡
Here is a quick look at how session revocation works behind the scenes in MongoDB.
🛠️ Session Revocation Logic
1. Single Device Logout (logout)
- Extracts the
refreshTokenfrom incoming HTTP cookies. - Verifies JWT signature and fetches the active session document where
revoke: false. - Marks
revoke = truein MongoDB and clears the HTTP-only cookie on the client.
javascript
export const logout = async (req, res) => {
try {
const incomingToken = req.cookies.refreshToken;
if (!incomingToken) return res.status(400).json({ message: "Token not found!" });
const decoded = jwt.verify(incomingToken, config.JWT_SECRET);
const session = await sessionModel.findOne({ _id: decoded.sessionId, revoke: false });
if (!session) return res.status(400).json({ message: "Invalid Token" });
session.revoke = true;
await session.save();
res.clearCookie("refreshToken");
res.status(200).json({ message: "Logout Successfully" });
} catch (error) {
res.status(400).json({ message: "Invalid or expired token" });
}
};
Top comments (0)