0

Heylo,

I'm building a (semi) REST API with Nodejs/Express as back and Phonegap/Cordova as front. For backend i'm using express with connect-mongo and mongoose as following :

express.cookieParser(),
express.session({
    secret: nconf.get('session:salt'),
    store: new mongoStore({url: nconf.get('database').url})
}),

for session validation on node i've create the following function inside my route.js file

var authenticate = function (req, res, next) {

if (req.session.user)
    next();
else
    res.error('access is not authentication');
}

Unfortunately PhoneGap and Cordova do not support cookies out of the box so i use localStorage to store session_id and wrap every server call to aggregate it to the url params.

Is there any elegant way to pre-load the session from mongoDB inside my authenticate function by the 'session_id' param without creating a Schema for the session collection and try querying it with mongoose?

Cheers,

-PK.

Pavel 'PK' Kaminsky
  • 796
  • 1
  • 10
  • 22

1 Answers1

0

Use the store.get method of your mongoStore. Try something like this:

var authenticate = function (req, res, next) {
  mongoStore.get(req.params.session_id, function (error, session) {
    if (error) {
      res.status(500).send(error);
      return;
    }
  }
  req.session = session;
  next();
}
Peter Lyons
  • 142,938
  • 30
  • 279
  • 274
  • unfortunately, the serialized session is different from the session object being injected by `connect-mongo`, so if i use the above as a middleware which being called after `express.session({ secret: nconf.get('session:salt'), cookie: {secure: false, maxAge: 300000}, store: mStore })` ill get an exception, if I reverse the middleware order so it will be deserialized before `connect-mongo` , then it will inject and override my loaded session object. catch-22. – Pavel 'PK' Kaminsky Apr 21 '14 at 19:46
  • to be more precise here is the deserialization failure as a gist https://gist.github.com/kaminskypavel/e4f19bdb43899fa09389 – Pavel 'PK' Kaminsky Apr 21 '14 at 20:11
  • Yeah you'll have to put a real session instance there in the way connect expects. I don't know those details off the top of my head though so I can't help with that aspect. – Peter Lyons Apr 21 '14 at 21:21