Two Levels Authorization Using NodeJS

Lets first figure out why we might need the two level authorizations specially while building production REST APIs.

1- Implementing CQRS (you can red more about CQRS in last two posts 1 & 2 )
2- Having non-user (Session) token authorization and a user token authorization
3-  You could also use it for logging or any kind of aspect oriented pre-processing functionality.

 

Building the Authorization Module

//Level 1
function level1_auth(req,res)
{
  var auth = true;
  if(!auth)
  {
    console.log('Non Authorized Level1.');
    throw ('Invalid Token');
  }
  else
    console.log('Authorized Level1.');
}

//Level 1
function level2_auth(req,res,next)
{
  var auth = false;
  if(!auth)
  {
    console.log('Non Authorized Level2.');
    res.status(403).send('Not Authorized');
  }
  else
    console.log('Authorized Level2.');
}

exports.level1_auth = level1_auth;
exports.level2_auth = level2_auth;

API

const express= require('express');
const authhandler = require('./authorization-handler');
var app = new express();

//Level 1
app.all('*',function(req,res,next){
  try{
    authhandler.level1_auth();
    next();
  }
  catch(ex)
  {
    res.status(403).send(ex)
  }
})

//Level 2
app.get('/get',authhandler.level2_auth,function(req,res,next)
{
  res.send('get command executed');
})

Thanks,

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s