Search code examples
node.jsexpressmiddlewarepassport.js

nodejs passport not logging out because of middleware


I am making a webapp using nodejs, express, mongoose and passport npm.

Earlier my login and logout functionality was working fine but now I had to add a functionality for checking if user is premium or normal user. So I made a middleware which is now causing problem in logging out. here are my codes.

In my index.js file an ajax request on /matchData is being called every second to get data depending on user type.

//ajax routes for json response
router.get('/matchData', isPremium);


//middleware causing problem
function isPremium(req,res,next){
    if(req.isAuthenticated()){
        if(req.user.type=='premium'){
            console.log("user is premium");
            Match.getMatchLatestData(function(err,match){
                if(err) throw err;
                res.send(match[0]);
            });
        }else{
            console.log("user is loggedin but not premium");
            Match.getMatchData(function(err,match){
                if(err) throw err;
                res.send(match[0]);
            });
        }
    }else{
        console.log("user not logged in");
        Match.getMatchData(function(err,match){
            if(err) throw err;
            res.send(match[0]);
        }); 
    }   
}

and in my user.js where my login and logout functionalty is as follows

//Login Routes
router.get('/login',isAuthenticated2, function(req, res, next) {
  res.render('user/login',{
    title:'login'
  });
});

router.post('/login',isAuthenticated2, passport.authenticate('local',{failureRedirect:'/users/login', failureFlash:'Invalid Email Id or Password'}),function(req,res){
    console.log('Authentication Successful');
    req.flash('success','You are logged in.');
    res.redirect('/');
});

//logout route
router.get('/logout',isAuthenticated,function(req,res){
    req.logout();
    req.flash('success','You have logged out');
    res.redirect('/');
});

function isAuthenticated(req, res, next) {
    if(req.isAuthenticated())
        return next();
    else{
        req.flash('error','Please Login First')
        res.redirect('/users/login');   
    }

}

function isAuthenticated2(req, res, next) {
    if(req.isAuthenticated()){
        req.flash('info','You are already logged in.')
        res.redirect('/');  
    }
    else
        return next();
}

now the problem is when I logout it displays flash msg successful but in my console it still shows I am logged in but not premium or I am premium, which is the only case if I am logged in.


Solution

  • Instead of using req.logout() try to use below snippet

    req.session.destroy(function (err) {
        res.redirect('/');
     });