Add basic auth for production mode

This commit is contained in:
Kimmo Puputti 2017-01-16 14:59:10 +02:00
parent 8af04d35cc
commit 9fb2495af8
4 changed files with 42 additions and 2 deletions

View file

@ -3,6 +3,7 @@
"version": "0.2.0",
"private": true,
"dependencies": {
"basic-auth": "^1.1.0",
"compression": "^1.6.2",
"express": "^4.14.0",
"helmet": "^3.3.0",

27
server/auth.js Normal file
View file

@ -0,0 +1,27 @@
const auth = require('basic-auth');
/**
* Create a basic authentication middleware function that checks
* against the given credentials.
*/
exports.basicAuth = (username, password) => {
if (!username || !password) {
throw new Error('Missing required username and password for basic authentication.');
}
return (req, res, next) => {
const user = auth(req);
if (user && user.name === username && user.pass === password) {
next();
} else {
res
.set({
'WWW-Authenticate': 'Basic realm="Authentication required"',
})
.status(401)
.end("I'm afraid I cannot let you do that.");
}
};
};

View file

@ -21,6 +21,7 @@ const helmet = require('helmet');
const compression = require('compression');
const path = require('path');
const fs = require('fs');
const auth = require('./auth');
const _ = require('lodash');
const React = require('react');
const { createServerRenderContext } = require('react-router');
@ -83,6 +84,13 @@ const app = express();
// See: https://www.npmjs.com/package/helmet
app.use(helmet());
// Use basic authentication when not in dev mode.
if (!dev) {
const USERNAME = process.env.BASIC_AUTH_USERNAME;
const PASSWORD = process.env.BASIC_AUTH_PASSWORD;
app.use(auth.basicAuth(USERNAME, PASSWORD));
}
app.use(compression());
app.use('/static', express.static(path.join(buildPath, 'static')));

View file

@ -876,14 +876,14 @@ babel-register@^6.16.0, babel-register@^6.18.0:
mkdirp "^0.5.1"
source-map-support "^0.4.2"
babel-runtime@6.11.6, babel-runtime@^6.0.0, babel-runtime@^6.9.0, babel-runtime@^6.9.1:
babel-runtime@6.11.6, babel-runtime@^6.9.1:
version "6.11.6"
resolved "https://registry.yarnpkg.com/babel-runtime/-/babel-runtime-6.11.6.tgz#6db707fef2d49c49bfa3cb64efdb436b518b8222"
dependencies:
core-js "^2.4.0"
regenerator-runtime "^0.9.5"
babel-runtime@^6.11.6, babel-runtime@^6.20.0:
babel-runtime@^6.0.0, babel-runtime@^6.11.6, babel-runtime@^6.20.0, babel-runtime@^6.9.0:
version "6.20.0"
resolved "https://registry.yarnpkg.com/babel-runtime/-/babel-runtime-6.20.0.tgz#87300bdcf4cd770f09bf0048c64204e17806d16f"
dependencies:
@ -943,6 +943,10 @@ base64-js@^1.0.2:
version "1.2.0"
resolved "https://registry.yarnpkg.com/base64-js/-/base64-js-1.2.0.tgz#a39992d723584811982be5e290bb6a53d86700f1"
basic-auth@^1.1.0:
version "1.1.0"
resolved "https://registry.yarnpkg.com/basic-auth/-/basic-auth-1.1.0.tgz#45221ee429f7ee1e5035be3f51533f1cdfd29884"
batch@0.5.3:
version "0.5.3"
resolved "https://registry.yarnpkg.com/batch/-/batch-0.5.3.tgz#3f3414f380321743bfc1042f9a83ff1d5824d464"