Fi Auth
Route authorization module for Node.js Express applications.
Installing
npm install --save fi-auth
Usage
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);
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 Function
to log with or a Boolean
. If true
it'll use console.log
.
-
authorizer: This is required and must be a Function
. This Function
runs on each request and should return the String
or Number
that will be compared against the allows
parameter value inside each route definition. The authorizer Function
return value will be attached to req.session.authorized
.
-
routes: An Array
with the routes to authorize:
- method: A
String
or an Array
of HTTP request method(s) to filter. If no method is specified it defaults to all. - path: A
String
or an Array
of strings with the route(s) path(s) to filter. - allows: A
String
or an Array
of authorization value(s) to compare with the authorizer method returned value.
Example configuration
{
debug: require('debug')('app:auth'),
authorizer: function (req) {
if (req.session.user) {
return req.session.user.admin && 'admin' || 'user';
}
return null;
},
routes: [{
path: '/api/users/count',
allows: 'admin'
}, {
method: 'GET',
path: '/api/users',
allows: 'admin'
}, {
method: ['POST', 'PUT', 'DELETE'],
path: ['/api/users', '/api/stuff'],
allows: 'admin'
}, {
method: ['POST', 'DELETE'],
path: '/api/content',
allows: ['user', 'admin']
}]
}