This commit is contained in:
Josh Harvey 2016-11-06 20:07:49 +00:00
parent 1771467474
commit 855546f886
7 changed files with 157 additions and 131 deletions

View file

@ -1,33 +1,23 @@
var http = require('http')
var https = require('https')
var express = require('express')
var bodyParser = require('body-parser')
var routes = require('./routes')
var plugins = require('./plugins')
var logger = require('./logger')
var configManager = require('./config-manager')
const fs = require('fs')
const http = require('http')
const https = require('https')
const express = require('express')
const routes = require('./routes')
const plugins = require('./plugins')
const logger = require('./logger')
var argv = require('minimist')(process.argv.slice(2))
const helmet = require('helmet')
const configManager = require('./config-manager')
const options = require('./options')
const pair = require('./pair')
const devMode = argv.dev || argv.http || options.http
module.exports = function (options) {
var app = express()
var server
app.use(helmet())
app.use(bodyParser.json())
const psqlUrl = options.postgresql
if (!psqlUrl) {
console.log('Missing postgresql entry in configuration file')
process.exit(1)
}
function run () {
const app = express()
const localApp = express()
const seedPath = options.seedPath || './seeds/seed.txt'
plugins.init(psqlUrl, seedPath)
console.log('DEBUG6')
plugins.init(seedPath)
return configManager.load()
.then(config => {
@ -35,42 +25,47 @@ module.exports = function (options) {
plugins.startPolling()
plugins.startCheckingNotification()
var authMiddleware
if (options.https) {
const serverOptions = {
key: options.https.key,
cert: options.https.cert,
requestCert: true
}
server = https.createServer(serverOptions, app)
authMiddleware = function (req, res, next) {
const deviceId = req.connection.getPeerCertificate().fingerprint
console.log(deviceId)
return pair.isPaired(deviceId)
.then(r => {
if (r) {
req.deviceId = deviceId
return next()
}
throw new Error('Unauthorized')
})
.catch(e => res.status(403).end())
}
} else {
server = http.createServer(app)
authMiddleware = function (req, res, next) {
return next()
}
const httpsServerOptions = {
key: fs.readFileSync(options.keyPath),
cert: fs.readFileSync(options.certPath),
requestCert: true
}
if (options.mock) logger.info('In mock mode')
const server = devMode
? http.createServer(app)
: https.createServer(httpsServerOptions, app)
return server
const port = devMode
? 3000
: 443
const localPort = 3030
const localServer = http.createServer(localApp)
if (options.devMode) logger.info('In dev mode')
const opts = {
app,
localApp,
devMode,
plugins
}
routes.init(opts)
server.listen(port, () => {
console.log('lamassu-server listening on port ' +
port + ' ' + (devMode ? '(http)' : '(https)'))
})
localServer.listen(localPort, 'localhost', () => {
console.log('lamassu-server listening on local port ' + localPort)
})
})
.catch(err => {
console.log(err)
process.exit(1)
})
}
module.exports = {run}