On my express server I'am tring to implement the following logic:
If the path is not /Login or /Register
And the request.session.authenticated is not true.
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()
}
}