29 January 2014

Readable NodeJS authorization

Today I'm going to post a nifty piece of code for NodeJS authorization.

Wow... It's been a while since I wrote something here.

Let's get dirty, first of all there are 2 reasonable assumptions:

  • You are using Express (or just Connect).
  • You are using Passport (for authentication). Passport is used to get a current user and his role from Request object.

For those who don't know: "authentication" is about finding out who the person is, classic example is email + password. Authorization is about what this person is allowed to do.

In this example for clarity I'm going to use Coffeescript, but it can be easily translated into JS (by using for example js2coffee.org).

What I wanted to do is to use rules in middleware style that works well with NodeJS async model.

The goal for authorization is to look something like that:

This is the cleanest API I could come up with.

Custom function can do 3 things:

  1. Allow action by returning next(true)
  2. Forbid action by returning next(false)
  3. Let the next middleware decide returning next(), if it was last function in a chain, than action is forbidden

So here's code that achieves it:

The beauty is that it works well with asynchronous calls just like good Node code should.

Thank you for reading my post! Have a few interesting things going on, hope some day I find time to write about them. :-)

No comments:

Post a Comment