Skip to content

Instantly share code, notes, and snippets.

@pbouzakis
Created April 18, 2012 19:53
Show Gist options
  • Save pbouzakis/2416094 to your computer and use it in GitHub Desktop.
Save pbouzakis/2416094 to your computer and use it in GitHub Desktop.
"use strict";
var Q = require("q");
var restify = require("restify");
module.exports = function (bnCloud) {
return function (serverRequest, serverResponse, next) {
var authHeaders = serverRequest.authorization;
var log = (serverRequest.log && serverRequest.log.trace.bind(serverRequest.log)) || console.log.bind(console);
function isPrivateUri() {
var id = serverRequest.params.id;
var ean = serverRequest.params.ean;
return serverRequest.path !== "/customers/" + id + "/docs/" + ean + "/thumbnail";
}
function send401Response() {
serverResponse.header("WWW-Authenticate", 'Basic realm="Sidearm says: Who goes there?"');
next(new restify.UnauthorizedError());
}
function auth(id, deviceToken) {
log("AUTH");
bnCloud.isAuthenticatedAsync(id, deviceToken)
.then(
function (isAuthenticated) {
log("AUTHENTICATED?", isAuthenticated, deviceToken);
if (isAuthenticated) {
next();
} else {
send401Response();
}
},
function (err) {
next(err);
}
);
}
if (isPrivateUri()) {
if (authHeaders.hasOwnProperty("basic")) {
var customerId = authHeaders.basic.username;
var deviceToken = authHeaders.basic.password;
if (customerId && deviceToken) {
return auth(customerId, deviceToken);
}
}
return send401Response();
}
log("PUBLIC URI", serverRequest.path);
return next();
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment