0

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.

  1. Is this the standard way to do this? No, please let me know how to achieve.
  2. whenever I browse localhost:3000 my req.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();
});*/
Bhagya
  • 43
  • 2
  • 11
  • Possible duplicate of [How to intercept node.js express request](http://stackoverflow.com/questions/11038830/how-to-intercept-node-js-express-request) – G07cha Sep 05 '16 at 12:05
  • what about q. 2 – Bhagya Sep 05 '16 at 12:06
  • Also, I suggest you take a look at [PassportJS](https://github.com/passport/express-4.x-local-example) for such cases as authorization. – G07cha Sep 05 '16 at 12:07
  • yes i am using passportJs only for login and all – Bhagya Sep 05 '16 at 12:08
  • the second question is more about debugging, can you show the code that used in `isAuthenticated` function? – G07cha Sep 05 '16 at 12:10
  • isAuthenticate() method present in req object that is commented for now – Bhagya Sep 05 '16 at 12:12
  • You getting redirected to `/user/login/` because `isAuthenticated` function doesn't return true, so you should provide/check your PassportJS-related code. – G07cha Sep 05 '16 at 12:15
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/122668/discussion-between-bhagya-and-konstantin-azizov). – Bhagya Sep 05 '16 at 12:16

1 Answers1

0

middleware come in handy here. define your middleware like

module.exports.isAuthenticated=function(req,res,next){

  if(req.isAuthenticated){
  return next();
  }
  next(error('user is not authorized'));
}

then in your route file

route.get('/home',auth.isAutheticated,goToHome);
Waqas Noor
  • 911
  • 6
  • 12