Consider following auth scenario with the following middleware:
const auth = async (req, res, next) => {
console.log("doing auth")
if(req.body.password === process.env.SECRET){
req.session.authenticated = true;
}
return next()
}
const redirect = (req, res, next) => {
console.log("check redirect")
if(req.session.authenticated) {
return "admin"
}
return "login"
}
and the following draw sequence:
route.draw(app).get(async (req, res) => {
res.render(
name,
routeUtils.getViewData(res),
)
}).post(auth, route.doRedirect(redirect))
route.doRedirect(redirect) only gets evaluated and executed once. Every subsequent time the redirect function is not called. If auth was valid it always returns admin no matter what and if not valid it is login. So for example you enter a password wrong the first time, even if you enter it a second time correctly, it fails.
I am wondering if this is a side effect of route being an instance of a class vs. purely functional.
A simple solution is to add the following middleware to the page:
const redirect = (req, res, next) => {
if(req.session.authenticated) {
return res.redirect(res.locals.route.get("admin").url(req.locale))
}
return res.redirect(res.locals.route.get("login").url(req.locale))
}
and changing
}).post(auth, route.doRedirect(redirect))
to
but it more or less is the same thing?