Reputation: 15
I'm currently working on an authentication system Mongoose (i'm new to it), and I would like some feedback on my approach to handling JWT token expiration in the context of user logout.
I have implemented a strategy to check the validity of JWT tokens by comparing the loggedoutAt
attribute in my user schema with the iat
(issued at) claim of the decoded JWT token. If the loggedoutAt
timestamp is present and greater than the iat
, I consider the token invalid and return a 401 status.
Here's a snippet of the relevant code:
export const auth = asyncHandler(async (req, res, next) => {
// 1-) Check if token exists
let token;
if (
req.headers.authorization &&
req.headers.authorization.startsWith("Bearer ")
)
token = req.headers.authorization.split(" ")[1];
if (!token) return next(new ApiError("Please login or sign up", 401));
// 2-) Check if token is not valid or if token is expired
const decodedToken = jwt.verify(token, process.env.JWT_SECRET_KEY);
// 3-) Check if user exists
const user = await User.findById(decodedToken.userId);
if (!user)
return next(new ApiError("Token invalid: User dose not exists", 401));
// 4-) Check if the user has been loggedout with this token
if (user.loggedoutAt) {
const loggedoutAtTimestamp = parseInt(
user.loggedoutAt.getTime() / 1000,
10
);
if (loggedoutAtTimestamp > decodedToken.iat)
return next(new ApiError("Token invalid: User logged out", 401));
}
req.user = user;
next();
});
And here is the log out function:
export const logout = asyncHandler(async (req, res, next) => {
req.user.loggedoutAt = Date.now();
await req.user.save();
res.status(200).json({ status: "logged out" });
});
My Questions:
Is this strategy a reasonable approach for handling token invalidation upon user logout, or are there better practices I should consider? Are there potential pitfalls or improvements I should be aware of in this implementation?
I appreciate any guidance or suggestions you can provide. Thank you!
Upvotes: 0
Views: 994
Reputation: 304
With your implementation, if a user is logged in from multiple devices, logging out from one device automatically logs the user out from other devices.
Take a look at this question and the answer on how to invalidate JWT Invalidating JSON Web Tokens
Upvotes: 1