title: Passport and Socket.IO - Keep logged in with Socket.IO?
body: <p>I'm using Express 4, Socket.IO 1.x and what ever is the newest Passport is. I can login, and stay logged in as long as I refresh my screen with in 120 seconds of each load (life time the session). I have socket.io running a "ping/pong" and when the server receives a pong, the session's expiration is updated and therefor still valid. If I refresh the screen after 120 seconds of the last load, req.isAuthenticated() comes back with false and kicks me out to the login. How to I keep myself logged in with socket.io?</p>
  
  <p>Here some relevant code: </p>
  
  <pre><code>var sessionMiddleware = session({
      store            : new RedisStore({}), // XXX redis server config
      secret           : 'Some Key!',
      cookie           : {maxAge: 120000},
      resave           : true,
      saveUninitialized: true
  });
  
  app.use(cookieParser()); // read cookies (needed for auth)
  app.use(bodyParser.urlencoded({extended: true}));
  app.use(sessionMiddleware);
  app.use(passport.initialize());
  app.use(passport.session());
  app.use(express.static('public'));
  app.use(flash());
  
  
  io.use(function(socket, next)
  {
      sessionMiddleware(socket.request, {}, next);
      //sessionMiddleware(socket.request, socket.request.res, next);
  });
  
  /**
   * Keeping the session alive through socket.io
   * Ping and Pong are reserved events on the client - so it's Ding and Dong for us!
   */
  function sendHeartbeat()
  {
      setTimeout(sendHeartbeat, 8000);
      io.emit('ding', {beat: 1});
  }
  
  app.get('/', function (req, res)
  {
      console.log('--------');
      console.log('From Get');
      console.log(req.session);
      console.log('--------');
      if(!req.isAuthenticated())
      {
          res.redirect('/login');
          return;
      }
  
      res.render('index', {sessionid: req.sessionID});
  });
  
  passport.use(new LocalStrategy(function (username, password, done)
      {
          console.log(username);
          console.log(password);
  
          db.query('SELECT * FROM `agents` WHERE `username` = ?', [username], function (err, rows)
          {
              if(err)
              {
                  console.log(err);
                  return done(err);
              }
              var ret = JSON.parse(JSON.stringify(rows));
  
              if(ret.length != 1)
              {
                  return done(null, false, {message: 'Incorrect username and/or password'});
              }
  
              if(!bcrypt.compareSync(password, ret[0].password))
              {
                  return done(null, false, {message: 'Incorrect username and/or password'});
              }
  
              return done(null, ret[0]);
          });
      }
  ));
  
  passport.serializeUser(function (user, done)
  {
      done(null, user.agent_id);
  });
  
  passport.deserializeUser(function (agent_id, done)
  {
      // Should use agent_id here - it's possibly faster.
      db.query('SELECT * FROM `agents` WHERE `agent_id` = ?', [agent_id], function (err, rows)
      {
          if(err)
          {
              console.log(err);
              return done(err);
          }
          var ret = JSON.parse(JSON.stringify(rows));
          console.log(ret[0]);
          done(null, ret[0]);
      });
  });
  
  app.get('/login', function (req, res)
  {
      if(req.isAuthenticated())
      {
          res.redirect('/');
          return;
      }
  
      res.render('login');
  });
  
  app.post('/login', passport.authenticate('local', {
          successRedirect: '/',
          failureRedirect: '/login',
          failureFlash   : true
      })
  );
  
  io.on('connection', function (socket)
  {
      console.log('--------');
      console.log('From IO');
      console.log(socket.request.session);
      console.log('--------');
      console.log('A socket with sessionID ' + socket.request.sessionID  + ' connected!');
  
      // Ping and Pong are reserved events on the client - so it's Ding and Dong for us!
       socket.on('dong', function (data)
       {
           // Keep session alive
           socket.request.session.touch().save(function(err)
           {
              if(err)
              {
                 console.log('Could not touch and save the session');
                 return;
              }
  
              console.log('GOT PONG');
           });
       });
  });
  
  setTimeout(sendHeartbeat, 8000);
  </code></pre>