Is it possible to get an express session by sessionID?

I have a NodeJS Express app that uses express-session. This works great, as long as session cookies are supported.

Unfortunately it also needs to work with a PhoneGap app that does not support cookies of any kind.

I am wondering: Is it possible to get an express session and access the data in that session, using the sessionID?

I am thinking I could append the sessionID as a querystring parameter for every request sent by the PhoneGap app like so:

https://endpoint.com/dostuff?sessionID=whatever

But I don't know how to tell express to retrieve the session.

Answers:

Answer

You can certainly create an express route/middleware that tricks express-session that the incoming request contains the session cookie. Place something like this before the session middleware:

app.use(function getSessionViaQuerystring(req, res, next) {
  var sessionId = req.query.sessionId;
  if (!sessionId) return res.send(401); // Or whatever

  // Trick the session middleware that you have the cookie;
  // Make sure you configure the cookie name, and set 'secure' to false
  // in https://github.com/expressjs/session#cookie-options
  req.cookies['connect.sid'] = req.query.sessionId;
  next();
});
Answer

Seems like req.cookies isn't accessible in my case. Here's another solution that recreates the session using the 'x-connect.sid' header (you may use any name or even a query param if you like).

Put this middleware after the session middleware

// FIRST you set up your default session like: app.use(session(options));

// THEN you recreate it using your/custom session ID
app.use(function(req, res, next){
	var sessionId = req.header('x-connect.sid');

	function makeNew(next){
    if (req.sessionStore){
      req.sessionStore.get(sessionId, function(err, session){
        if (err){
          console.error("error while restoring a session by id", err);
        }
        if (session){
          req.sessionStore.createSession(req, session);
        }
        next();
      });
    } else {
      console.error("req.sessionStore isn't available");
      next();
    }
	}

	if (sessionId) {
		if (req.session){
			req.session.destroy(function(err){
				if (err) {
					console.error('error while destroying initial session', err);
				}
				makeNew(next);
			});
		} else {
			makeNew(next);
		}
	} else {
		next();
	}
});

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.