A Node.js HTTP reverse proxy library for quick and dirty CouchDB proxy authentication.
Install from NPM
npm install couchdb-auth-proxy -S
And import into your project
import couchdbProxy from "couchdb-auth-proxy";
const couchdbProxy = require("couchdb-auth-proxy");
Note: Ensure proxy authentication is enabled on your CouchDB server. This is as simple as adding
{couch_httpd_auth, proxy_authentication_handler}
to the list of active authentication handlers in your configuration. See the CouchDB Docs for more info.
This library generates an HTTP server request function from two arguments: a user context method and some options. This method will work with Express/Connect apps as well as the plain Node.js HTTP server.
Here is an example proxy that authenticates every request as a super admin:
const server = http.createServer(couchdbProxy(function(req) {
// admin party!
return {
name: null,
roles: [ "_admin" ]
};
}));
In CouchDB, users are represented with a user context object. These are objects with name
and roles
fields. Usually this information comes from a document in the _users
database, however we can also generate it from other means.
Your proxy can complete asynchronous tasks, great for authenticating against other databases or services. You can return a promise, or provide a third argument for a callback.
const server = http.createServer(couchdbProxy(function(req, res, next) {
const token = req.get("Authorization");
db.authenticateToken(token, (err, user) => {
if (err) return next(err);
next(null, {
name: user.name,
roles: []
});
});
}));
userCtxFn
(Function, required) - Method called on every request, with the requestreq
and responseres
as arguments. This method should return a plain object withname
androles
fields, representing the authenticated user. To run an async task, return a promise or pass a third argumentnext
for a callback.options
(Object) - Options to configure the proxy.options.target
(String) - The URL of the CouchDB server to proxy to. This server must have proxy authentication enabled. Defaults tohttp://localhost:5984
.options.secret
(String) - The CouchDB secret used to sign proxy tokens and cookies. This is only required ifcouch_httpd_auth/proxy_use_secret
is enabled on CouchDB (which is recommended).options.via
(String) - The name of the proxy to add to theVia
header. This is so consumers of the HTTP API can tell that the request was directed through a proxy. This is optional and theVia
header will be excluded when not provided.options.headerFields
(Object) - A map of custom header fields to use for the proxy. This should match what is declared in CouchDBcouch_httpd_auth
configuration, underx_auth_roles
,x_auth_token
, andx_auth_username
. This is the default map:
{ "username": "X-Auth-CouchDB-UserName", "roles": "X-Auth-CouchDB-Roles", "token": "X-Auth-CouchDB-Token" }
options.info
(Object) - Some JSON serializable value that will be injected into the CouchDB's root info document response.