1 year ago
#382288

Nima
Delete the Session of a logged in user which is later deleted by the Admin
In my Express API, when a user is still logged in and the admin deletes that particular user from the database, I want the session data of that user to be deleted so it can no longer have access (I'm using Connect-PG-Simple as the session store).
I have already implemented a logic in my DELETE method so that if the user itself deletes its own account, it gets logged out and the session will be deleted:
// If the user is Admin, don't log out or delete session of the admin after user deletion
if (req.user.role === "ADMIN") {
res.status(200).json({ message: "User Deleted Successfully" });
} else {
// If the user is not Admin, log out the deleted user and delete its session and clear its cookie
req.logout();
req.session.destroy((err) => {
if (err) {
next(err);
} else {
res.clearCookie("connect.sid");
res.status(200).json({ message: "User Deleted Successfully" });
}
});
}
The problem is that when the admin deletes the user and the user tries to access the data, my app gets this error on every request:
failed to deserialize user out of session
These are my login and serialize/deserialize logic:
Serialize/Deserialize:
// Store user id in session
passport.serializeUser((user, done) => {
done(null, user.id);
});
// Fetch user data from session
passport.deserializeUser(async (id, done) => {
try {
// Fetching user data of the stored id from session
const findUser = await db.query(selectUserById, [id]);
const user = findUser.rows[0];
return done(null, user);
} catch (err) {
return done(err);
}
});
Login:
const login = (req, res, next) => {
passport.authenticate("local", (err, user, info) => {
if (err) {
return next(err);
}
// If no user is found
if (!user) {
return res.status(401).json(info);
}
// If user is found
req.login(user, (err) => {
if (err) {
return next(err);
} else {
return res.status(200).json({
message: "Login Successful",
user: {
id: req.user.id,
name: req.user.name,
email: req.user.email,
},
});
}
});
})(req, res, next);
};
Is there any way I can avoid that error and delete the session data of that specific user?
javascript
node.js
postgresql
express
passport.js
0 Answers
Your Answer