I have a NodeJS/Express application where I am using PassportJS for authentication.
I have the following routes:
router.get("/profile", isUser, (req, res) => {
res.render("profile");
});
router.post("/post-something", isUser, (req, res) => {
db.post(...);
res.json({ success: true });
});
router.get("/login", (req, res) => {
res.redner("login");
});
router.post("/login", (req, res) => {
req.logIn(...);
res.redirect("profile");
});
router.delete("/logout", (req, res) => {
req.logout(...);
res.redirect("login");
});
where isUser
is a middleware function which checks that the user is logged in:
- if the user is logged in, continue.
- if the authInfo is set, it means there was an error (e.g. the user is still logged in despite the user document having been deleted causing passportJS to fail when trying to find the user), in which case I wish to log the user out.
- if the user is not logged in, the user should be taken to the log in page.
function isUser(req, res, next) {
if (req.user) {
return next();
}
else if (req.authInfo.message === "user not found") {
return res.redirect("/logout");
}
else {
return res.redirect("/login");
}
Firstly, in the scenario where the user is not logged in and I wish to redirect to the login page, how do I distinguish between the login GET route and the login POST route? If a user for example sends the post request to /post-something
will the redirect also assume that the method to be used is still the POST method causing me to attempt to log in directly instead of opening the log in page?
Secondly, in the scenario where an error has occurred and I wish to log out, how does my app know that I am switching from a GET or POST request to now redirect to a DELETE route before redirecting back to a GET route after logging out?
sorry if this is a dumb question but I do not understand how these redirects work when it comes to the HTTP methods ):