From 9326ee4c7358bbd53fee6e9a89e05252358c3fc2 Mon Sep 17 00:00:00 2001 From: Moritz Schmidt Date: Sat, 30 Sep 2017 14:13:59 +0200 Subject: [PATCH] allow array of basic auth users --- app.js | 11 ++--------- config.js.example | 2 +- lib/setup-basic-auth.js | 29 +++++++++++++++++++++++++++++ 3 files changed, 32 insertions(+), 10 deletions(-) create mode 100644 lib/setup-basic-auth.js diff --git a/app.js b/app.js index 45f5a92..0492190 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,14 +15,7 @@ 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 })) diff --git a/config.js.example b/config.js.example index dbe2265..56a2d0c 100644 --- a/config.js.example +++ b/config.js.example @@ -12,7 +12,7 @@ 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 }, 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) + })) +}