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;
Middlewares
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 run, and for example login to user / login, I logged in to save a session in memory and store the id in req.session.user_id, after this I put those middlewares so that if I wanted to enter any of those logs endpoint simply redirected me, but in the case of logout, what I wanted was that if I logged in just closed the session by req.session .user_id = undefined (Is this okay?).
It happens that the login is activated, if I try to login, recover, register redirects me, but when I try to logout I also redirect without closing the session, the first middleware is executed, but I put it so that run the 2nd, as I see it read sequentially and there should be a next one 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 so to say to the 2nd middleware from my route using use.
I edit I've done it in 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();
}
}