In this lesson, you will learn how to immediately invalidate a user’s access across your entire system the moment an account is deactivated.
When a user is suspended, simply toggling an isActive flag in your database is often insufficient. If your application relies on stateless JSON Web Tokens (JWTs) or active server-side session stores, that user could remain "logged in" until their token naturally expires. To enforce immediate revocation, you must implement a mechanism to destroy these sessions instantly.
The Revocation Strategy
The most reliable approach is to pair your database flag with an active session blacklist or a versioning strategy.
- The Database Flag: First, update the user record to
isActive: false. - The Security Version: Add a
security_stamportoken_versioncolumn to your user model. Every time a user logs in, include this version in their JWT payload. - The Validation Middleware: In your authentication middleware, perform a quick check:
async function protect(req, res, next) {
const user = await User.findById(req.user.id);
// 1. Check account status
if (!user.isActive) {
return res.status(403).json({ message: "Account suspended." });
}
// 2. Validate token version
if (req.user.tokenVersion !== user.tokenVersion) {
return res.status(401).json({ message: "Session revoked." });
}
next();
}
Clearing Refresh Tokens
If you use refresh tokens to issue new access tokens, these are usually stored in a database (like Redis or PostgreSQL). When you deactivate an account, you must run a cleanup query to delete all refresh tokens associated with that specific userId. This prevents the client from using a valid refresh token to bypass your session middleware and request a new, "fresh" access token.
By combining an active status check with a token version comparison, you create a "kill switch." Even if a user has a valid-looking JWT, your application will reject it the moment you increment their tokenVersion or update their status in the database.
Key Takeaway: Deactivation is only effective if you invalidate both the current session and the means to generate new ones by clearing refresh tokens and verifying the account status on every request.