connect-redis-sessions

Session store using redis-sessions for Connect

connect-redis-sessions

Is a connect or express middleware to simply use the redis sessions. With redis sessions you can handle multiple sessions per user_id.

// get the modules 
var express = require( "express" );
var cookieParser = require( "cookie-parser" );
var ConnectRedisSessions = require( "connect-redis-sessions" );
var app = express();
 
 
// configute express 
app
    .use( express.query() )
    .use( cookieParser() )
    .use( ConnectRedisSessions( { app: "myappname" } ) )
 
// listen for requests 
app.use( function( reqres ){
    if( req.query.login ){
        // upgrade a session to a redis session by a user id 
        req.session.upgrade( req.query.user_id );
    }
    if( req.sessin.id && req.query.logout ){
        // kill the active session 
        req.session.destroy();
    }
    res.end( "Hello express redis sessions" );
});

npm install connect-redis-sessions

  1. you have to get the express middleware init method by
    var ConnectRedisSessions = require( "connect-redis-sessions" );
  2. init your express or express server
    var app = require( "express" )();
  3. init the express cookie parser
    app.use( express.cookieParser() );
  4. use express redis sessions as middleware app.use( ConnectRedisSessions( { app: "myappname" } ) );

Attension: If you're using Express < 4.x then please use version 0.x otherwise use version 1.x of connect-redis-sessions. It schould work with connect and the older Express, but there could be eventual issues due to the new Express 4.x api behaviour i haven't found yet.

ConnectRedisSessions( options )

To init the session handling just add the options object as argument.

  • app : ( String|Function required )
    A simple string as appname or a function to calc the name on every request. The function addes to arguments req and callback.
_getAppName = function( reqcallback ){ callback( null, "staticname" ) };
  • cookie : ( Object )
    Cookie configuration. If nothing is set a browser session cookie will be used.
    • maxAge ( Number ) The maximum age of the generated cookie.
    • path ( String, default = / )
      The cookie path
    • httpOnly ( String, default = true )
  • trustProxy : ( Boolean, default = false ) Only accept https cookies
  • port : ( Number, default = 6379 ) Redis port
  • host : ( String, default = 127.0.0.1 ) Redis host
  • namespace : ( String, default = rs ) The namespace prefix for all Redis keys used by the redis session module.
  • wipe : ( Number, default = 600 ) The interval in second after which the timed out redis sessions are wiped. No value less than 10 allowed.
  • ttl : ( Number, default = 7200 ) Redis session timeout to wipe the session on idle time. Must be over 10. If you set a value < 10 the module will use 10 instead.

After you have initializes the session handling every connect/express request object will contain a key called session. Within this Object you cann save rudimental keys of types String, Number and Boolean. These keys will be saved at the end of the request and will be availible within the next request.

And there are some additional methods and metadata

  • req.session.id : ( String ) Your session token
  • req.session.d : ( Object ) Just a small helper to get all data woithin the session without handling the properties and method names. All keys under req.session.d[ ? ] will also be availible under req.session[ ? ]
  • req.session._meta : ( Object )
    Contains the redis sessions meta data.
    • id : ( String|Number )
      the global user id
    • r : ( Number ) the session read count
    • w : ( Number ) the session write count
    • idle : ( Number ) the session idle time
    • ttl : ( Number ) the session ttl

upgrade a empty session to a real redis session by upgrading the session with the user_id.

Arguments

  • user_id : ( String|Number required ): The user id this session should belong to.
  • ttl : ( Number optional; default = options.ttl ): Optinal ttl for this session. If not set the ttl defined in options would be used. Must be over 10. If you set a value < 10 the module will use 10 instead.
  • cb : ( Function optional ): Callback method with the results.

Get all session of the logged in id.

Arguments

  • cb : ( Function ): Callback method with the results.

Get all session of an app.

Arguments

  • dt : ( Function default = 600 ): Get the app session history back in seconds.
  • cb : ( Function ): Callback method with the results.

Query the amount of active session within the last 10 minutes (600 seconds).

Arguments

  • dt : ( Function default = 600 ): Get the app activity history back in seconds.
  • cb : ( Function ): Callback method with the results.

Kill the current active session

Arguments

  • cb : ( Function optional ): Callback method.

Kill ALL session of the given user_id.

Arguments

  • cb : ( Function optional ): Callback method.

Changed session data will allways be saved at the end of a request. But with this method you can force the saving of the session object to redis-sessions.

Arguments

  • cb : ( Function optional ): Callback method.

Reload the session from redis sessions

Arguments

  • cb : ( Function optional ): Callback method.

Will return the internal instance of RedisSessions. You can use this to handle sessions of other users.

Returns

( RedisSessions ): The raw redis sessions module.

// get the modules 
var express = require( "express" );
var cookieParser = require( "cookie-parser" );
var bodyParser = require( "body-parser" );
var logger = require( "morgan" );
var ConnectRedisSessions = require( "connect-redis-sessions" );
var app = express();
 
// get the appname by the first part of the url 
var _getAppName = function(reqcb) {
    var appname;
    appname = req._parsedUrl.pathname.split("/")[1];
    if (appname != null) {
        cb(null, appname);
    } else {
        // if nothing is returned a empty session will be availible 
        cb(null);
    }
};
 
fnCRS = ConnectRedisSessions( { app: _getAppName, ttl: _timeSecDay, cookie: { maxAge: _timeSecDay * 1000 } } );
 
// configute express 
_timeSecDay = 60 * 60 * 24
app
    .use( logger( "dev" ) )
    .use( express.query() )
    .use( bodyParser() )
    .use( cookieParser() )
    .use( fnCRS )
 
 
// an example how to get the internal redis-sessions instance out of the connect-redis-sessions module 
redisSessionsInstance = fnCRS.handler.rds;
 
// listen for requests 
app.use( function( reqres ){
    console.log( req.session );/*
        {
            "id": null,
            "d": {}
        }
    */
    res.end( "no knwon user" );
});
// listen for requests 
app.use( function( reqres ){
    if( req.session.id == void( 0 ) ){
        res.end( "user not logged in" );
    } else {
        res.end( "user " + req.session._meta.id + " is logged in" );
    }
});
// listen for requests 
app.use( function( reqres ){
    var user_id = "myuser_id" // code to get your user_id  
    req.session.upgrade( user_id, req.query.sessionttl, function(){
        console.log( req.session );/*
            {
                "id": "myuser_id",
                "d": {},
                "_meta": {
                    "id": "myuser_id",
                    "r": 1,
                    "w": 1,
                    "ttl": 86400,
                    "idle": 0
                }
            }
        */
        res.end( "user " + user_id + " has logged in" );
    }); 
});
// listen for requests 
app.use( function( reqres ){
    req.session.meaning = 42;
    req.session.foo = "bar";
    console.log( req.session );/*
        {
            "id": "myuser_id",
            "meaning": 42,
            "foo": "bar",
            "d": {
                "meaning": 42,
                "foo": "bar"
            },
            "_meta": {
                "id": "myuser_id",
                "r": 2,
                "w": 1,
                "ttl": 86400,
                "idle": 10
            }
        }
    */
    res.end( "data written to session" );
 
});
// listen for requests 
app.use( function( reqres ){
    res.end( "session data " + req.session.foo + " says " + req.session.meaning );
 
});
// listen for requests 
app.use( function( reqres ){
    req.session.soid( function( errsessions ){
        if( err ){
            res.end( "ERROR" );
            return
        }
        res.end( JSON.stringify( sessions ) );/*
            [{
                id: 'myuser_id',
                r: 3,
                w: 2,
                ttl: 86400,
                idle: 10
            },
            {
                id: 'myuser_id',
                r: 1,
                w: 1,
                ttl: 7200,
                idle: 56040
            }] 
        */
    });
});
// listen for requests 
app.use( function( reqres ){
    req.session.destroy()
});
VersionDateDescription
v1.2.02014-11-28Added ttl to upgrade method + Issues by thynson
v1.0.32014-09-11Added return of sessionhandler object on initialisation
v1.0.22014-04-25Small bugfix for cookie handling
v1.0.12014-03-17Updated readme with external express/connect middleware
v1.0.02014-03-17fixed cookie set for express 4.x
v0.2.02014-03-07express 0.4.0 support
v0.1.52013-12-04Added method SessionObject.getRedisSessionsModule() to receive the internal redis session instance
v0.1.42013-11-20Fixed No d supplied error on upgrade
v0.1.32013-10-15Fixed error on missing callback
v0.1.22013-10-15Added example check for a logged in user to readme
v0.1.12013-10-15Fixed module to be compatible with express and changed readme examples from connect to express
v0.1.02013-10-04Initial commit
NameDescription
redis-sessionsThe redis session module this middleware module is based on
tcs_node_authAuthentication module to handle login and register with a integrated mail double-opt-in logic.
NameDescription
systemhealthNode module to run simple custom checks for your machine or it's connections. It will use redis-heartbeat to send the current state to redis.
node-cacheSimple and fast NodeJS internal caching. Node internal in memory cache like memcached.
rsmqA really simple message queue based on Redis
task-queue-workerA powerful tool for background processing of tasks that are run by making standard http requests.
soyerSoyer is small lib for serverside use of Google Closure Templates with node.js.
grunt-soy-compileCompile Goggle Closure Templates ( SOY ) templates inclding the handling of XLIFF language files.
backlunrA solution to bring Backbone Collections together with the browser fulltext search engine Lunr.js

Copyright © 2013 Mathias Peter, http://www.tcs.de

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.