More refactoring on Trader

This commit is contained in:
Maciej Małecki 2014-04-14 15:16:53 +02:00
parent 05fef31fce
commit 1f3c59dbc0
6 changed files with 88 additions and 277 deletions

View file

@ -23,17 +23,44 @@ var express = require('express');
var fs = require('fs');
var LamassuConfig = require('lamassu-config');
var routes = require('./routes');
var Trader = require('./trader');
var PostgresqlInterface = require('./protocol/db/postgresql_interface');
module.exports = function (options) {
var app = express();
var connectionString;
var server;
var config;
var trader;
var db;
connectionString = options.postgres ||
'postgres://lamassu:lamassu@localhost/lamassu';
config = new LamassuConfig(connectionString);
db = new PostgresqlInterface(connectionString);
trader = new Trader(db);
config.load(function (err, config) {
if (err) {
console.error('Loading config failed');
throw err;
}
trader.configure(config);
trader.startPolling();
});
config.on('configUpdate', function () {
config.load(function (err, config) {
if (err) {
return console.error('Error while reloading config');
}
trader.configure(config);
console.log('Config reloaded');
});
});
app.use(express.logger());
app.use(express.favicon());
@ -56,28 +83,27 @@ module.exports = function (options) {
server = https.createServer(serverOptions, app);
}
config.load(function(err, conf) {
if (err) { console.log(err); process.exit(1); }
var authMiddleware = function (req, res, next) {
req.device = {};
return next();
};
var authMiddleware = function (req, res, next) { return next(); };
if (options.https) {
authMiddleware = function(req, res, next) {
var fingerprint = req.connection.getPeerCertificate().fingerprint;
var e = new Error('Unauthorized');
e.status = 401;
if (options.https) {
authMiddleware = function(req, res, next) {
var fingerprint = req.connection.getPeerCertificate().fingerprint;
var e = new Error('Unauthorized');
e.status = 401;
config.isAuthorized(fingerprint, function (err, device) {
if (err) { return next(e); }
if (!device) { return next(e); }
req.device = device;
next();
});
};
}
config.isAuthorized(fingerprint, function (err, device) {
if (err) { return next(e); }
if (!device) { return next(e); }
req.device = device;
next();
});
};
}
routes.init(app, conf, config, authMiddleware);
});
routes.init(app, trader, authMiddleware);
return server;
};