mark
mark

Reputation: 62836

How to enumerate all the sessions in nodejs + express?

I am trying to write a simple nodejs server with sessions and user authentication. Here is the code:

var express = require('express'),
    app = express(),
    fs = require('fs'),
    passport = require('passport'),
    jade = require('jade'),
    BasicAuthStrategy = require('passport-http').BasicStrategy,
    webRootDir = __dirname + '/web',
    templatesDir = __dirname + '/templates/';

passport.use(new BasicAuthStrategy(
    function (username, password, cb) {
        "use strict";
        cb(null, username);
    }
));

app.use(express.logger());
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({secret: 'd6151b7e-8997-4187-a95e-29ce08450094'}));
app.use(passport.initialize());
app.use(passport.authenticate('basic', { session: false }));
app.use(express.favicon());
app.use(app.router);
app.use(express['static'](webRootDir));
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
app.set('view engine', 'jade');
app.engine("jade", jade.__express);

app.get('/', function (req, res) {
    "use strict";
    res.render(templatesDir + 'index', {
        user: req.user
    });
});

app.listen(8080);

Now I would like to enumerate all the sessions created since the server is up (I am not seeking session persistency) and inspect their contents. How can I do it?

Upvotes: 0

Views: 5367

Answers (2)

loretoparisi
loretoparisi

Reputation: 16301

In case you are using the popular Redis session backed for express, this is implemented here, so you just have to call the redisStore.all method, so you can do a promise like

WebApp.prototype.allSessions = function() {
        var self=this;
        return new Promise((resolve, reject) => {
            self.store.all((error, results) => {
                if( error ) return reject(err);
                else return resolve(results);    
            });
        });
    }//allSessions

where the session is backed by Redis

self.store=new RedisStore(redisConfig); // session store
// express session options
var sessionOptions={
    store: self.store,
    secret: oauthConfig.secret,
    cookie: {
        /** when the session gonna expire */ 
        expire: new Date( Date.now() + self._options.session.expiresInMsec ),
        /** how long the session lasts [ms]*/
        maxAge: self._options.session.expiresInMsec
    },
    resave: false, // avoid race conditions
    saveUninitialized: false // avoid race conditions
}

and the you can enumerate live sessions at every login like:

var oAuthStrategy = new OAuth2Strategy(oAuthOptions, function(accessToken, refreshToken, profile, done) {

            self.allSessions()
            .then(results => {
                console.log(results);
            })
//...

Upvotes: 1

Timothy Strimple
Timothy Strimple

Reputation: 23070

It depends on which session store you're using. A session store is not required to provide a mechanism for getting all stored sessions.

However, the default Connect in-memory session store (which you should not use in production) provides a .all function which will allow you to get all of the sessions.

sessionStore.all(function(err, sessions) {
    // if err handle err
    // iterate over sessions array
});

Upvotes: 4

Related Questions