I am looking to check user is authenticated or not before they browse something for that I have written this code.
router.use(function (req, res, next) {
console.log(req);
if(req.isAuthenticated()){
console.log("if......");
return next();
}else{
if (req.url === '/users/login' || req.url === '/users/register'){
console.log("if......2");
return next();
}else{
if (req.url === '/'){
console.log("if......3");
res.redirect('/users/register');
}else{
res.redirect('/users/login');
}
}
}
});
Now I have two questions to clear.
- Is this the standard way to do this? No, please let me know how to achieve.
- whenever I browse
localhost:3000
myreq.url = /user/login
I am surprised with that too. I don't know how its even possible.
But may be cache or something not sure to clear this I must inform, Before that I had code some thing like below which was meant to intercept or validate user when he hits localhost:3000
but now I have commented that entire code.
// Get Homepage
router.get('/'/*, ensureAuthenticated*/, function(req,res){
res.render('index');
});
/*function ensureAuthenticated(req, res, next){
if(req.isAuthenticated()){
return next();
}else{
res.redirect('/users/login');
}
}
router.use(function (req, res, next) {
console.log('Time:', Date.now());
next();
});*/