How to create a session middleware?

Sat Nov 19 2016 18:19:51 GMT+0100 (CET), Peter Širka

How to create a session middleware?

We create a simple middleware

You can save the code below as your-app/definitions/session.js:

const COOKIE = '__session';
const TIMEOUT = '10 minutes';
const SESSION = {};

// We register a new middleware `session`
F.middleware('session', function(req, res, next, options, controller) {

    var cookie = req.cookie(COOKIE);
    var ip = req.ip.hash().toString();

    // A simple prevention for session hijacking
    if (cookie) {
        var arr = cookie.split('|');
        if (arr[1] !== ip)
            cookie = null;
    }

    if (!cookie) {
        cookie = U.GUID(15) + '|' + ip;

        // Writes cookie
        res.cookie(COOKIE, cookie);
    }

    var session = SESSION[cookie];
    if (session)
        req.session = session;
    else
        SESSION[cookie] = req.session = {};

    // Extends session timeout
    req.session.ticks = F.datetime;
    next();
});

// Clears expired sessions
F.on('service', function(counter) {

    // each 2 minutes
    if (counter % 2 !== 0)
        return;

    var ticks = F.datetime.add('-' + TIMEOUT);

    Object.keys(SESSION).forEach(function(key) {
        var session = SESSION[key];
        if (session.ticks < ticks)
            delete SESSION[key];
    });
});
  • constant SESSION contains all active sessions
  • constant TIMEOUT contains expiration time for a session
  • constant COOKIE contains a cookie name

Usage

Now we can use the middleware, so create/modify a controller e.g. /your-app/controllers/default.js:

exports.install = function() {
    F.route('/', view_index, ['#session']);
};

function view_index() {
    // this === controller
    var self = this;

    if (self.session.counter === undefined)
        self.session.counter = 0;

    self.session.counter++;
    self.view('index');
}

What have we done in the code above?

  • we created a route to homepage F.route('/', action, [flags])
  • the route contains session middleware, which we created
  • then we used controller.session in the controller's action

Extend middleware by adding e.g. events

Now it's very easy to extend functionality of middleware. So I extend the code below:

F.middleware('session', function(req, res, next, options, controller) {

    // ...
    // ...
    // ...

    var session = SESSION[cookie];
    if (session)
        req.session = session;
    else {
        SESSION[cookie] = req.session = {};

        // When the session is created then framework emits the event "session-new"
        F.emit('session-new', req, res, req.session);
    }

    // ...
    // ...
    // ...
});

// Clears expired sessions
F.on('service', function(counter) {

    // ...
    // ...
    // ...

    Object.keys(SESSION).forEach(function(key) {
        var session = SESSION[key];
        if (session.ticks < ticks) { 
            delete SESSION[key];

            // When the session is expired then framework emits the event "session-remove"
            F.emit('session-remove', session);
        }
    });

    // ...
    // ...
    // ...    
});

Usage:

You can use the code below in each .js file on the server-side in Total.js.

F.on('session-new', function(req, res, session) {
    // new session
});

F.on('session-remove', function(session) {
    // session is removed
});

How to set the middleware to multiple routes together?


Tags

Follow us

Latest blogs
Flow v5.1
Thu Jun 28 2018 19:22:41 GMT+0200 (CEST)
Total.js Dashboard v6.0
Mon Apr 23 2018 16:05:59 GMT+0200 (CEST)
Flow v5.0.0
Mon Apr 16 2018 12:32:11 GMT+0200 (CEST)
REST Azure DocumentDB in Node.js / Total.js
Mon Mar 26 2018 09:38:41 GMT+0200 (CEST)
How do I transform ErrorBuilder output?
Mon Jan 29 2018 09:22:49 GMT+0100 (CET)

Latest comments
Not only for Total.js. You can communicate with different websocket servers.
Peter Širka
Mon Apr 23 2018 20:08:20 GMT+0200 (CEST)
hellow every one
umar
Sun Apr 22 2018 10:05:35 GMT+0200 (CEST)
hehehshshshshdhsd
Amaury
Sat Mar 24 2018 19:46:54 GMT+0100 (CET)
asdasd
getrgerg
Tue Mar 20 2018 15:07:31 GMT+0100 (CET)
Is WEBSOCKETCLIENT only for internal ws connections between totaljs apps?
Stelios Stephanua
Fri Mar 16 2018 06:04:22 GMT+0100 (CET)
Total.js is amazing! ;)
Leonardo Hessel
Tue Dec 19 2017 19:51:15 GMT+0100 (CET)
It's easy, just set e.g. `res.status = 404`.
Peter
Thu Nov 16 2017 07:54:11 GMT+0100 (CET)
Yes, it's valid.
Peter
Thu Nov 16 2017 07:53:06 GMT+0100 (CET)
How do we set the status code in custome middleware?
Nabeel
Mon Oct 02 2017 10:31:40 GMT+0200 (CEST)
Node... Awesome applications.
oscar
Thu Aug 31 2017 02:21:59 GMT+0200 (CEST)
Awesome!
Tema
Wed May 10 2017 06:33:13 GMT+0200 (CEST)