How to redirect all paths except two if a condition is not met in Express

Viewed 44

On my express server I'am tring to implement the following logic:

  1. If the path is not /Login or /Register

  2. And the request.session.authenticated is not true.

  3. Redirect all request to /Login.

In other words , pseudocode :

function()
    {
        if (req.session.authenticated !== true && path !== '/Login')
            res.redirect('/Login')
    }


How can i write this function in Express with app.get() or similar ?

app.get( path , (req, res) => 
{
  // ??
})

------------------------------------------- After edited --------------------------

So , I tried this :

app.use(redirect())

function redirect(req, res, next) 
{
  if (req.session.authenticated !== true && req.path !== '/Login/Login.html' || req.session.authenticated !== true && req.path !== '/Register/Register.html') 
    {
      res.redirect('/Login/Login.html');
      return next()
    }
}

But , I got the following error :

  if (req.session.authenticated !== true && req.path !== '/Login/Login.html' || req.session.authenticated !== true && req.path !== '/Register/Register.html')
          ^

TypeError: Cannot read property 'session' of undefined

I guess that for some reason this function does not have acess to the request object which is weird. How can I make it acess the request ? I thought all middleware functions would have acess to the request.

------------------------------------2nd Edit------------------------------------

In my case the middleware function above only works if you save it to a variable and then use app.use() calling the variable the function was saved in.

So that would be :


app.use(redirectMe)

let redirectMe = function redirect(req, res, next) 
{
  if (req.session.authenticated !== true && req.path !== '/Login/Login.html' || req.session.authenticated !== true && req.path !== '/Register/Register.html') 
    {
      res.redirect('/Login/Login.html');
      return next()
    }
}
2 Answers

You can write something like an authentication middleware for this.

function redirect(req, res, next) {
        if (req.session.authenticated !== true && req.path !== '/Login' && req.path !== '/Register') {
            res.redirect('/Login');
            return
        }
    }

And the you just need to export that function and you can use it as a middleware in your routes. Something like this:

app.get('/profile', redirect(), (req, res) => {
  //Some code here
});

Declare a function in a golobal variable as shown below

let verifyLogin = (req, res,next){ 
        if(req.session.authenticated)
        { 
          next()
        } else {
          res.redirect('/login')
        }
    }

The above function is called from app.get() as shown below

 app.get('path', verifyLogin, (req, res)=>{
             //
    })
Related