diff --git a/app.js b/app.js index 45f5a92..dd16632 100644 --- a/app.js +++ b/app.js @@ -1,11 +1,11 @@ var express = require('express') -var basicAuth = require('express-basic-auth') var bodyParser = require('body-parser') var morgan = require('morgan') var path = require('path') var serveStatic = require('serve-static') var config = require('./config') +var setupBasicAuth = require('./lib/setup-basic-auth') var Manager = require('./lib/manager') var Missions = require('./lib/missions') var Mods = require('./lib/mods') @@ -15,18 +15,14 @@ var app = express() var server = require('http').Server(app) var io = require('socket.io')(server) -if (config.auth && config.auth.username && config.auth.password) { - var basicAuthUsers = {} - basicAuthUsers[config.auth.username] = config.auth.password - app.use(basicAuth({ - challenge: true, - users: basicAuthUsers - })) -} +setupBasicAuth(config, app) app.use(bodyParser.json()) app.use(bodyParser.urlencoded({ extended: false })) -app.use(morgan('dev')) + +morgan.token('user', function (req) { return req.auth ? req.auth.user : 'anon' }) +app.use(morgan(config.logFormat || 'dev')) + app.use(serveStatic(path.join(__dirname, 'public'))) var logs = new Logs(config) diff --git a/config.js.example b/config.js.example index dbe2265..7c2bb1a 100644 --- a/config.js.example +++ b/config.js.example @@ -12,10 +12,11 @@ module.exports = { '@mod1', '@mod2', ], - auth: { // If both username and password is set, HTTP Basic Auth will be used + auth: { // If both username and password is set, HTTP Basic Auth will be used. You may use an array to specify more than one user. username: '', // Username for HTTP Basic Auth password: '', // Password for HTTP Basic Auth }, prefix: "", // Prefix to all server names suffix: "", // Suffix to all server names + logFormat: "dev", // expressjs/morgan log format }; diff --git a/lib/setup-basic-auth.js b/lib/setup-basic-auth.js new file mode 100644 index 0000000..7f3a6ac --- /dev/null +++ b/lib/setup-basic-auth.js @@ -0,0 +1,29 @@ +var basicAuth = require('express-basic-auth') + +function getBasicAuthUsers (configAuth) { + var basicAuthUsers = {} + if (configAuth.username && configAuth.password) { + configAuth = [configAuth] + } + + configAuth.forEach(function (user) { + basicAuthUsers[user.username] = user.password + }) + + return basicAuthUsers +} + +module.exports = function (config, app) { + if (!config.auth) { + return + } + + if (!config.auth.username && !config.auth.password && !Array.isArray(config.auth)) { + return + } + + app.use(basicAuth({ + challenge: true, + users: getBasicAuthUsers(config.auth) + })) +}