List of logged in users in an Express app

I've setup basic user authentication using this http://mherman.org/blog/2015/01/31/local-authentication-with-passport-and-express-4/#.Vufc1fmLTIW

In my app I need to have a list of users who are currently logged in. So, I decided to keep this information on user object.

var Account = new Schema({
     username: String,
     email: String,
     online: {type: Boolean, default: false} 
 });

 var User = mongoose.model('Account', Account);

When a user logs in I update online property on User object to 'true' and when she logs out to 'false':

router.post('/login', function(req, res, next) {
    passport.authenticate('local', function(err, user, info) {
        if (err) {
        return next(err); 
    }
    if (!user) {
        return res.send({ success : false, info: info.message});
    }
    req.login(user, loginErr => {
        if (loginErr) {
        return next(loginErr);
    }
    req.session.cookie.maxAge = 10 * 60 * 1000;

    var id = user['_id'];
    var update = {'$set': {'online' : 'true'}};
    var callback = function (err, data) {
        if (err) return next(err);  
    };
    Users.findByIdAndUpdate(id, update, callback);

    return res.send({ success : true});
    });      
  })(req, res, next);
 });

 router.get('/logout', function(req, res) {   
      var id = req.user['_id'];
      var update = {'$set': {'online' : 'false'}};
      var callback = function (err, data) {
           if (err) return next(err);   
      };
      Users.findByIdAndUpdate(id, update, callback);

     req.logout();
     res.redirect('/');
 });

Everything worsks just fine, but I need somehow to set online property on User object to 'false' when cookies expire. Please help!

Answers


The only viable options I can come up with at the moment, and which I believe is quite common, is to use a timeout if no direct action to terminate the session has been called.

Based on the lifespan of your cookies, you can set a timeout on the server (setTimeout) that will invalidate the session/set online status to false if it triggers. If the user does anything before the timeout triggers, stop the timeout, and create a new one (Which is basically the same as you should be doing on your cookie).


Need Your Help

Subset large .csv file at reading in R

r csv subset

I have a very large .csv file (~4GB) which I'd like to read, then subset.

Every Tab is having same data in the recyclerview

android json android-fragments android-recyclerview android-tablayout

hi everyone i have created tabs using JSONS each tab contains recycler view where the required data of that tab will be displayed there but where as in output same data is displaying in every tab and