accosine / hapi-relax

Wraps nano's API as hapi server methods and seamlessly authenticates with CouchDB via cookie
BSD 2-Clause "Simplified" License
4 stars 1 forks source link

Build StatusCode ClimateTest CoverageDependency Status

hapi-relax

hapi plugin that registers server methods using nano and extends it by taking care of cookie authentication

Introduction

hapi-relax enhances your hapi server by an interface for a specified CouchDB database.
If you're using cookie authentication on top of basic-auth you can also pass a username and password. Just relax and stop worrying about authentication because the plugin will check if you are authorized. If not it will use nano's auth method to get a cookie and use that in a further request. But you won't notice because that all happens internally.
It will also update its cookie when CouchDB sends a new cookie in the headers.

Usage

var Hapi = require('hapi');
var server = new Hapi.Server();
var options = { nano: { db: 'testDb' } };

server.connection({ port: 80 });

server.register({ register: require('hapi-relax'), options }, function(err) {
});

server.start();

The plugin takes the following options:

API

nano's API remains unchanged

Example

var Hapi = require('hapi');

var server = new Hapi.Server();
server.connection({ port: 8080 });

var plugins = [{
  register: require('hapi-relax'),
  options: {
    nano: {
      url: 'http://localhost:5984',
      db: 'db1'
    },
    user: 'root',
    password: 'secret'
  }
},
{
  register: require('hapi-relax'),
  options: {
    nano: {
      url: 'http://localhost:5984',
      db: 'db2'
    },
    user: 'alice',
    password: 'rabbit',
    prefix: 'db2'
  }
}];

server.register(plugins, function (err) {
  if (err) {
    throw err;
  }
});

server.route({
    method: 'GET',
    path: '/db1/{key}',
    handler: function (request, reply) {
      var key = encodeURIComponent(request.params.key);
      server.methods.nano.get(key, function (err, body, headers) {
        if (err && err.reason === 'missing') {
          reply('Document does not exist').code(404);
        }
        else {
          reply(body);
        }
      });
    }
});

server.route({
    method: 'GET',
    path: '/db2/{key}',
    handler: function (request, reply) {
      var key = encodeURIComponent(request.params.key);
      server.methods.db2.get(key, function (err, body, headers) {
        if (err && err.reason === 'missing') {
          reply('Document does not exist').code(404);
        }
        else {
          reply(body);
        }
      });
    }
});

server.start(function () {
  console.log('Server running at:', server.info.uri);
});