From 8e2e071abf1e0d119514d59f2c3da951c53c279b Mon Sep 17 00:00:00 2001 From: tigerbot Date: Mon, 29 May 2017 13:41:09 -0600 Subject: [PATCH] implemented storage of tunnel tokens --- lib/app.js | 2 +- lib/tunnel-manager.js | 45 ++++++++++++++++++++++++++++++++++++++++--- 2 files changed, 43 insertions(+), 4 deletions(-) diff --git a/lib/app.js b/lib/app.js index 8ac1eda..e150402 100644 --- a/lib/app.js +++ b/lib/app.js @@ -171,7 +171,7 @@ module.exports = function (myDeps, conf, overrideHttp) { }).then(function (result) { console.log('got a token from the tunnel server?'); result.owner = session.id; - deps.tunneler.add(result); + return deps.tunneler.add(result); }); /* }); diff --git a/lib/tunnel-manager.js b/lib/tunnel-manager.js index 48be059..d0a3e58 100644 --- a/lib/tunnel-manager.js +++ b/lib/tunnel-manager.js @@ -1,9 +1,38 @@ 'use strict'; module.exports.create = function (deps, config) { + var PromiseA = require('bluebird'); + var fs = PromiseA.promisifyAll(require('fs')); var stunnel = require('stunnel'); var activeTunnels = {}; + var tokensPath = require('path').join(__dirname, '..', 'var', 'tokens.json'); + var storage = { + all: function () { + var tokens; + try { + tokens = require(tokensPath); + } catch (err) { + tokens = {}; + } + + return PromiseA.resolve(Object.keys(tokens).map(function (key) { + return tokens[key]; + })); + } + , save: function (result) { + var tokens; + try { + tokens = require(tokensPath); + } catch (err) { + tokens = {}; + } + + tokens[result.jwt] = result; + return fs.writeFileAsync(tokensPath, JSON.stringify(tokens), 'utf8'); + } + }; + function addToken(data) { if (!data.tunnelUrl) { var decoded; @@ -11,11 +40,12 @@ module.exports.create = function (deps, config) { decoded = JSON.parse(new Buffer(data.jwt.split('.')[1], 'base64').toString('ascii')); } catch (err) { console.warn('invalid web token given to tunnel manager', err); - return; + return PromiseA.reject(err); } if (!decoded.aud) { console.warn('tunnel manager given token with no tunnelUrl or audience'); - return; + var err = new Error('missing tunnelUrl and audience'); + return PromiseA.reject(err); } data.tunnelUrl = 'wss://' + decoded.aud + '/'; } @@ -50,8 +80,17 @@ module.exports.create = function (deps, config) { addToken({ jwt: jwt, owner: 'config' }); }); } + storage.all().then(function (stored) { + stored.forEach(function (result) { + addToken(result); + }); + }); return { - add: addToken + add: function (data) { + return addToken(data).then(function () { + return storage.save(data); + }); + } }; };