Skip to content
This repository was archived by the owner on Nov 27, 2020. It is now read-only.
This repository was archived by the owner on Nov 27, 2020. It is now read-only.

route.doRedirect passed function evaluates once #104

@maxneuvians

Description

@maxneuvians

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

}).post(auth, redirect)

but it more or less is the same thing?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions