bouncerjs
Activity based authorization module for Node.
Install
npm install bouncerjs --save
Setup
Activities
Activities are actions that will be performed by a user. Say we got a model that represents a blog post. Users can view, create, update and delete these posts. Therefore we got four activities, namely post:view
, post:create
, post:update
and post:delete
. Each activity requires different tests to determine whether or not a user is allowed to perform it. Let's take a closer look at the post:view
activity. Every user is allowed to view a certain post, if the post is public. If it is not public, only admins and the user that is the owner of the post are allowed to view it. With bouncerjs, you can define such assertions in a declarative way. Have a look at the following example:
var activities = post: { return 'OR' 'post:isPublic' paramspostId 'post:belongsToUser' paramsuser paramspostId 'user:isMemberOfGroup' paramsuser 'admin' ; } ;
We've created the activity post:view
that returns a set of assertions. These assertions are chained with the operator OR
. In this case bouncerjs will serially test each assertion. As soon as one assertion succeeds, bouncerjs will gains access to the respective activity.
Assertions
Now, that we've defined a set of assertions, we need to implement them.
var assertions = post: { // Your logic to test that the post is public. var post = postId; post; } { // Your logic to test that the post belongs to the given user. var post = postId; post; } user: { // Your logic to test that the user belongs to the given group. ifusergroup != group return ; return ; } ;
Configuration
Ok, we have defined the activites and implemented the assertions. Now we need to configure bouncerjs. Therefore we instantiate bouncerjs with the previously created activities and assertions. We also provide two callbacks. onNotAuthenticated
will be called when a user is not authenticated. onNotAuthorized
will be called when a user tries to perform an activity he is not allowed to.
var Bouncer = ; var bouncer = // Pass the defined activities and assertions activities: activities assertions: assertions // Middleware handler when user is not authenticated { ; } // Middleware handler when user not authorized { // For example: pass the error from the assertion ; } ; moduleexports = bouncer;
Use
Now we can user the bouncer instance to protect our routes. Therefore we use the activity
method. This method returns a middleware function that handles the authorization.
var express = ;var app = ;var PostsController = ; // Require the previously created bouncer instancevar bouncer = ; app; var server = app;
Documentation
Work in progress!