Creating roleFactory to check if req.session.role === ‘admin’

list of middleware bundled with connect

NOTE: most/all of these modules are not bundled with express or connect, but the list can give you an idea of some usable modules.

Express routing functions use internal middleware during their processing cycle, which can be overriden to add extra functionality. An example would be to add custom headers to your HTML output.

Lets create a middleware factory that can be passed into a route handler as an argument, after the route and before the callback. This factory will check if theres anything assigned to req.session.role. If there isnt, show no-auth message, if auth, continue the execution of the route handler. We will also create a route that will set req.session.role = 'admin'

‘roleFactoryExample.js’

var express = require('express');
var cookieParser = require('cookie-parser');
var session = require('express-session');

var app = express();

app.use(cookieParser());
// had to set saveUn... & resave or else depreciation error
app.use(session({
  secret: 'adsasdas',
  saveUninitialized: true,
  resave: true
}));

// to be passed as arg to route handler
var roleFactory = function(role) {
  return function(req, res, next) {
    if (req.session.role && req.session.role.indexOf(role) != -1) {
      // continues the execution of the route handler
      next();
    } else {
      // cancels the execution of the route handler, sends err msg
      res.send('you are not authenticated!');
    }
  }
}

app.get('/', roleFactory('admin'), function(req, res, next) {
  res.send('welcome to the app!!!');
});

app.get('/auth', function(req, res, next) {
  req.session.role = 'admin';
  res.send('you are authenticated!!');
});

app.listen(8000);

using the roleFactory internal middleware function we change the order of execution from app.get('/') to roleFactory('admin') ===THEN===> app.get('/')