diff --git a/package.json b/package.json index 96bf8b0..1cb94d0 100644 --- a/package.json +++ b/package.json @@ -29,6 +29,7 @@ "compression": "=1.6.2", "connect-static-file": "=1.1.2", "express": "=4.14.0", + "express-basic-auth": "=0.2.3", "express-winston": "=2.1.2", "helmet": "=3.4.0", "opbeat": "=4.7.0", diff --git a/src/basic-auth.js b/src/basic-auth.js new file mode 100644 index 0000000..2a22837 --- /dev/null +++ b/src/basic-auth.js @@ -0,0 +1,17 @@ +const basicAuth = require('express-basic-auth'); +const { BASIC_AUTH_ENABLED } = require('./consts'); + +function basicAuthHandler(username, password) { + return process.env.BASIC_AUTH_USERNAME === username && process.env.BASIC_AUTH_PASSWORD === password; +} + +if (BASIC_AUTH_ENABLED) { + module.exports = basicAuth({ + authorizer: basicAuthHandler, + challenge: true + }); +} else { + module.exports = (req, res, next) => next(); +} + + diff --git a/src/consts.js b/src/consts.js index ddae159..e38eb6d 100644 --- a/src/consts.js +++ b/src/consts.js @@ -4,5 +4,6 @@ module.exports = { SERVE_DIR: IN_TEST ? 'site/' : process.argv[process.argv.length - 1], PORT: process.env.PORT || 5000, IN_TEST, - IN_PRODUCTION: process.env.NODE_ENV === 'production' + IN_PRODUCTION: process.env.NODE_ENV === 'production', + BASIC_AUTH_ENABLED: process.env.BASIC_AUTH_USERNAME && process.env.BASIC_AUTH_PASSWORD }; diff --git a/src/server.js b/src/server.js index de5097a..51e8a88 100755 --- a/src/server.js +++ b/src/server.js @@ -3,20 +3,22 @@ console.log('Starting Server...'); const app = require('express')(); -const utils = require('./consts'); +const consts = require('./consts'); const compression = require('compression'); const helmet = require('helmet'); const opbeat = require('opbeat').start({ - active: utils.IN_PRODUCTION + active: consts.IN_PRODUCTION }); const logging = require('./logging'); const staticFiles = require('./static-files'); const handle404 = require('./404'); +const basicAuth = require('./basic-auth'); // Custom Middleware app.use(logging); +app.use(basicAuth); app.use(staticFiles.indexHandle); app.use(staticFiles.static); app.use(handle404); @@ -26,7 +28,7 @@ app.use(compression({ level: 9 })); app.use(helmet()); app.use(opbeat.middleware.express()); -const server = app.listen(utils.PORT, function () { +const server = app.listen(consts.PORT, function () { console.log('Server started on ' + server.address().port); });