Home

Awesome

Kansas Express

Kansas API usage limiter Middleware for Express.

Build Status

Install

Install the module with: npm install kansas-express --save

Overview

Kansas Express offers the following types of Middleware:

The Consume Middleware

Add the consume middleware on every resource you want to apply Rate Usage Limiting. The Consume middleware requires a Kansas instance.

var kansas = require('kansas');
var kansasConsume = require('kansas-express/consume');

// initialize kansas
exports.kansas = kansas();

// initialize Consume Middleware
var consume = kansasConsume(exports.kansas);

// add to any route
app.get('/api/clients', consume.use());
app.get('/api/clients', theAppLogicHandler);

The Consume Middleware will check that the API Token is properly set in the request Headers. If it exists and it has available units to consume, then the API call will be allowed and the remaining usage units will be propagated on the response Headers.

Configuring the Consume Middleware

Use the method setup() to configure the Consume Middleware, it accepts an Object with any of the following properties

var kansasConsume = require('kansas-express/consume');

// create two instances of Consume Middleware
var consume = kansasConsume(api);
var consumeHeavy = kansasConsume(api);

// The heavy API call will consume 5 units
consumeHeavy.setup({
    consumeUnits: 5,
});

// add route for paginated clients
app.get('/api/clients', consume.use());
app.get('/api/clients', theAppLogicHandler);

// add route for all clients
app.get('/api/allclients', consumeHeavy.use());
app.get('/api/allclients', anotherAppLogicHandler);

Consume Error Handling and Types of errors

By default the Consume Middleware will generate these HTTP Codes on error:

Error TypeHTTP Code
Token Header not set401
Token Header set but invalid value401
Token does not exist in store401
Usage Limit Exceeded429
Any other error generated401

If you define your own Error Handler it will be invoked with two arguments, res the response object and error the error object. All errors will have a httpcode property, a number indicating the suggested HTTP error Code.

Consume Success Handling

The Consume Middleware will add a response HTTP Header named X-RateLimit-Remaining and have as value the remaining usage units. You can change the Header's name using the setup() method or you can have your own Success Handler.

The custom Success Handler will be invoked with the following three arguments:

The Count Middleware

Add the Count middleware on every resource you want to count usage. The Count middleware requires a Kansas instance.

var kansas = require('kansas');
var kansasCount = require('kansas-express/count');

// initialize kansas
exports.kansas = kansas();

// initialize Count Middleware
var apiCount = kansasCount(exports.kansas);

// add to any route
app.get('/api/clients', apiCount.use());
app.get('/api/clients', theAppLogicHandler);

Configuring the Count Middleware

Use the method setup() to configure the Count Middleware, it accepts an Object with any of the following properties

var kansasCount = require('kansas-express/count');

// create an instance of the Count Middleware
var apiCount = kansasCount(kansas);

// Consume 5 units by default
apiCount.setup({
    consumeUnits: 5,
});

Count Error Handling and Types of errors

By default the Count Middleware will generate these HTTP Codes on error:

Error TypeHTTP Code
Token Header not set401
Token Header set but invalid value401
Token does not exist in store401
Any other error generated401

If you define your own Error Handler it will be invoked with two arguments, res the response object and error the error object. All errors will have the httpcode property, a number indicating the suggested HTTP error Code.

Count Success Handling

The custom Success Handler will be invoked with the following three arguments:

The Manage Middleware

The Manage Middleware will add Token managing routes as a convenience for creating your manage panels and dashboards. By default the following routes will be created when the middleware is initialized:

MethodRouteAction
POST/tokenCreate a new Token
GET/tokenFetch all owner's token items
GET/token/:tokenFetch a single token item
DELETE/token/:tokenDelete a token
var kansas = require('kansas');
var kansasManage = require('kansas-express/manage');

// initialize kansas
var api = kansas();

var manage = kansasManage(api);
manage.setup({
  // the provide callback is required
  // it will provide the ownerId and policyName
  // to the middleware
  provide: function(req, res) {
    return {
      ownerId: 'hip',
      policyName: 'free',
    };
  }
});

// pass the express instance to initialize routes
manage.addRoutes(app);

Configuring the Manage Middleware

Use the method setup() to configure the Manage Middleware, it accepts an Object with any of the following properties

About the "provide" Callback

Kansas Express is agnostic to the stack used to track sessions, user objects or authentication. So you need to provide the ownerId and the policy the owner belongs to for each request. This happens with the provide callback.

The Provide callback will get invoked with two arguments, the Request and Response Express objects. Thus you have complete control on how the request will turn out, you can perform authentication checks and reject it there and then or provide the required data and pass control to next.

It is expected that the Provide callback will produce an Object with two keys ownerId and policyName either synchronously or asynchronously. To provide the result asynchronously you need to return a Promise that conforms to the Promises/A+ spec.

manage.setup({
    provide: function(req, res) {
      return new Promise(function(resole, reject) {
        doSomethingAsync(function(udo){
          resolve({
              ownerId: udo.id,
              policyName: udo.policy,
          });
        });
      });
    }
});

Manage Error Handling and Types of errors

By default the Manage middleware will generate these HTTP Codes on error:

Error TypeHTTP Code
Max Tokens per User Limit Exceeded403
Any other error generated500

If you define your own Error Handler it will be invoked with two arguments, res the response object and error the error object. All errors will have a httpcode property, a number indicating the suggested HTTP error Code.

Manage Success Handling

By default the Manage Middleware will send these HTTP Codes on success:

Success TypeHTTP Code
A request was processed ok200
A Delete operation was successful204

All responses will be JSON encoded and the Content-Type Header will have a forced value of application/json. You can change all that by using your own Success Handler.

The custom Success Handler will be invoked with the following three arguments:

Release History

License

Copyright (c) 2014 Thanasis Polychronakis. Licensed under the MIT license.