UNPKG

cozy-proxy

Version:

Cozy Proxy redirects requests properly to the right application of the Cozy platform depending on given path. It also handles authentication to the Cozy for users and devices.

85 lines (73 loc) 2.65 kB
// Generated by CoffeeScript 1.10.0 var Client, cache, client, dsHost, dsPort, extractCredentials, logger, updateCredentials; Client = require('request-json').JsonClient; logger = require('printit')({ date: false, prefix: 'lib:remote_access' }); cache = {}; dsHost = 'localhost'; dsPort = '9101'; client = new Client("http://" + dsHost + ":" + dsPort + "/"); if (process.env.NODE_ENV === "production" || process.env.NODE_ENV === "test") { client.setBasicAuth(process.env.NAME, process.env.TOKEN); } extractCredentials = module.exports.extractCredentials = function(header) { var authDevice, password, username; if (header != null) { authDevice = header.replace('Basic ', ''); authDevice = new Buffer(authDevice, 'base64').toString('utf8'); username = authDevice.substr(0, authDevice.indexOf(':')); password = authDevice.substr(authDevice.indexOf(':') + 1); return [username, password]; } else { return ["", ""]; } }; updateCredentials = module.exports.updateCredentials = function(callback) { return client.post("request/access/all/", {}, function(err, res, accesses) { var access, i, len; cache = {}; if (err != null) { logger.error(err); return typeof callback === "function" ? callback(err) : void 0; } else { if (accesses != null) { for (i = 0, len = accesses.length; i < len; i++) { access = accesses[i]; cache[access.value.login] = access.value.token; } } return typeof callback === "function" ? callback() : void 0; } }); }; module.exports.isAuthenticated = function(header, callback) { var isPresent, login, password, ref; ref = extractCredentials(header), login = ref[0], password = ref[1]; isPresent = (cache[login] != null) && cache[login] === password; if (isPresent || process.env.NODE_ENV === "development") { return callback(true); } else { return updateCredentials(function() { return callback((cache[login] != null) && cache[login] === password); }); } }; module.exports.isTargetAuthenticated = function(credential, callback) { if (!((credential.shareID != null) && (credential.token != null))) { return callback(false); } return client.get("data/" + credential.shareID, function(err, result, doc) { var target; if (err || ((doc != null ? doc.targets : void 0) == null)) { return callback(false); } else { target = doc.targets.filter(function(t) { return t.token === credential.token || t.preToken === credential.token; }); target = target[0]; return callback(target != null, doc, target); } }); };