fi-auth v2.0.2
Fi Auth
Route authorization module for Node.js Express applications.
Installing
npm install --save fi-authUsage
var auth = require('fi-auth');Initialization
You must call it with your Express' app instance, to attach the routes, and a configuration object. It's important to initialize the Express' session before you configure Fi Auth:
var session = require('express-session');
var express = require('express');
var auth = require('fi-auth');
var app = express();
app.use(session());
auth(app, config);
/* And now your routes... */
app.get('/', function (req, res, next) {
//...
});Configuration
The configuration Object must have an authorizer function and a route array. The debug parameter is optional but recommended.
IMPORTANT: All routes are allowed by default!
debug: This option can be a
Functionto log with or aBoolean. Iftrueit'll useconsole.log.authorizer: This is required and must be a
Function. ThisFunctionruns on each request and should return theStringorNumberthat will be compared against theallowsparameter value inside each route definition. The authorizerFunctionreturn value will be attached toreq.session.authorized.routes: An
Arraywith the routes to authorize:- method: A
Stringor anArrayof HTTP request method(s) to filter. If no method is specified it defaults to all. - path: A
Stringor anArrayof strings with the route(s) path(s) to filter. - allows: A
Stringor anArrayof authorization value(s) to compare with the authorizer method returned value.
- method: A
Example configuration
{
debug: require('debug')('app:auth'),
authorizer: function (req) {
/* IMPORTANT: This is just a simple example */
/* Check if there's a user in session */
if (req.session.user) {
/* Check whether the user has 'admin' role */
return req.session.user.admin && 'admin' || 'user';
}
/* There's no user in session */
return null;
},
/* Routes authorization definition */
routes: [{
/* All request methods are filtered */
path: '/api/users/count', /* On this route path only */
allows: 'admin' /* And allows 'admin' only */
}, {
method: 'GET', /* Only GET requests are filtered */
path: '/api/users', /* On this route path only */
allows: 'admin' /* And allows 'admin' only */
}, {
method: ['POST', 'PUT', 'DELETE'], /* Only POST, PUT and DELETE requests are filtered */
path: ['/api/users', '/api/stuff'], /* On this route paths only */
allows: 'admin' /* And allows 'admin' only */
}, {
method: ['POST', 'DELETE'], /* Only POST, PUT and DELETE requests are filtered */
path: '/api/content', /* On this route path only */
allows: ['user', 'admin'] /* And allows both 'user' and 'admin' */
}]
}