Search code examples
node.jsexpresssessionpassport.jsexpress-session

Express-Session - Is there a way to store data in a session outside of an ExpressJS route?


I have a passportJS callback that when a new user tries to authenticate, I don't want the new users data to be stored in a database but rather in a express-session to access later, is this possible?

Currently my code is:

function facebookAuthenticate(accessToken, refreshToken, profile, done) {
    User.findOne({ facebookID: profile._json.id }, (err, foundUser) => {
        if (foundUser) {
            done(err, foundUser);
        } else {
            global.authenticationID = { facebookID: profile._json.id };
            done(err, null)
        }
    });
}

But as global variable isn't user specific it can only be used for one authentication at a time.

Ideally I would like something that works along these lines but of course I don't have access to the req variable outside of a route:

function facebookAuthenticate(accessToken, refreshToken, profile, done) {
    User.findOne({ facebookID: profile._json.id }, (err, foundUser) => {
        if (foundUser) {
            done(err, foundUser);
        } else {
            req.session.authenticationID = { facebookID: profile._json.id };
            done(err, null)
        }
    });
}

Many Thanks.


Solution

  • That's correct, the global variable is out-of-scope outside the routes. A very hard-core method is to store the session data on a file the disk and read it back whenever needed. But there are some limitations. Using jwt auth you can store the data on the browser sessions and cookies.

    a simple idea is to create a session on express first,

    var sessions    = require("client-sessions");
    app.use(sessions({
          cookieName: 'expSessions', // cookie name dictates the key name added to the request object
          secret: 'somesuperSecret', // should be a large unguessable string
          duration: 24 * 60 * 60 * 1000, // how long the session will stay valid in ms
          activeDuration: 1000 * 60 * 5, // if expiresIn < activeDuration, the session will be extended by activeDuration milliseconds
            cookie: {
                path: '/', // cookie will only be sent to requests under '/api'
                maxAge: 60000, // duration of the cookie in milliseconds, defaults to duration above
                ephemeral: false, // when true, cookie expires when the browser closes
                httpOnly: true, // when true, cookie is not accessible from javascript
                secure: true // when true, cookie will only be sent over SSL. use key 'secureProxy' instead if you handle SSL not in your node process
            }
        }));
    

    Alternatively, there are a number of npm packages available for session handling like 'express-session'. Have a look around. Good luck!