I have the following routes and the following middlewares
router.use(logged.unlogged);
router.use("/logout",logged.logged);
router.route("/login").get(login.login_get).post(login.login_post);
router.route("/recuperar").get(recuperar.recuperar_get).post(recuperar.recuperar_post);
router.route("/registrar").get(registrar.registrar_get).post(registrar.registrar_post);
router.route("/logout").get(logout);
module.exports=router;
Middleware
var logged=function(req,res,next){
if(req.session.user_id!=undefined){
console.log("logged if");
next();
}
else{
console.log("logged error");
return res.redirect("/");
}
}
var unlogged=function(req,res,next){
if(req.session.user_id!=undefined){
console.log("El usuario ya esta logeado",Date.now());
return res.redirect("/");
}
else{
console.log("unlogged else",req.session.user_id);
next();
}
}
module.exports={
logged:logged,
unlogged:unlogged
}
What happens is the following, when I execute, and for example enter user/login, I log in, a session is saved in memory and I store the id in req.session.user_id, after this I put those middlewares so that if I wanted to enter some of those logged in endpoints would simply redirect me, but in the case of logout, what I wanted was that if I was logged in I would simply log out by setting req.session.user_id=undefined (is this ok?).
It happens that I log in, the session is activated, if I try to enter login, retrieve, register redirects me, but when I try to enter logout it also redirects me without closing the session, the first middleware is executed, but I put it so that the 2nd, as I see it reads it sequentially and there should be a next to read the second, I could put it using something like req.path.indexOf("logout") , but my question is if there is another way to give it more importance like this tell the 2nd middleware from my route using use.
Edit I have done it this way that seems more logical to me.
var unlogged=function(req,res,next){
if(req.session.user_id!=undefined){
if(req.path.indexOf("logout")>0)next();
console.log("El usuario ya esta logeado",Date.now());
return res.redirect("/");
}
else{
console.log("unlogged else",req.session.user_id);
next();
}
}
I don't see a need for a middleware to log out the user. It would just check right there if you are logged in. If it is, I destroy the session, then redirect to the index (and if it's not logged in, too).