Created
August 13, 2015 14:50
-
-
Save blech75/f56b07c37cedcccf6077 to your computer and use it in GitHub Desktop.
simple node-based static web server that does HTTP auth
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // based on http://expressjs.com/starter/static-files.html and | |
| // https://davidbeath.com/posts/expressjs-40-basicauth.html | |
| var express = require('express'); | |
| var basicAuth = require('basic-auth'); | |
| var fs = require('fs'); | |
| var app = express(); | |
| // pull config from env | |
| var USERNAME = process.env['HTTP_USER'] || 'user'; | |
| var PASSWORD = process.env['HTTP_PASSWORD'] || 'password'; | |
| var REALM = process.env['HTTP_REALM'] || 'Authorization Required'; | |
| var DOCROOT = process.env['HTTP_DOCROOT'] || 'public'; | |
| var INDEX = process.env['HTTP_INDEX'] || 'index.html'; | |
| var PORT = process.env['PORT'] || 3000; | |
| var DISABLE_HTTP_AUTH = process.env['DISABLE_HTTP_AUTH']; | |
| var docroot_path = __dirname + '/' + DOCROOT; | |
| // test for existence of dir to serve & error out if it doesn't exist | |
| try { | |
| fs.statSync(docroot_path).isDirectory(); | |
| } catch(e) { | |
| console.log("Error: Path " + docroot_path + " doesn't exist."); | |
| return(e.errno); | |
| } | |
| var staticMiddleware = express.static(docroot_path, { | |
| 'index' : INDEX | |
| }); | |
| var authMiddleware = function(req, res, next) { | |
| function unauthorized(res) { | |
| res.set('WWW-Authenticate', 'Basic realm=' + REALM); | |
| return res.sendStatus(401); | |
| } | |
| var user = basicAuth(req); | |
| if (!user || !user.name || !user.pass) { | |
| return unauthorized(res); | |
| } | |
| if (user.name === USERNAME && user.pass === PASSWORD) { | |
| return next(); | |
| } else { | |
| return unauthorized(res); | |
| } | |
| }; | |
| var startupMsg = 'Serving ' + docroot_path + ' on port ' + PORT; | |
| if (DISABLE_HTTP_AUTH) { | |
| app.use('/', staticMiddleware); | |
| } else { | |
| app.use('/', authMiddleware, staticMiddleware); | |
| startupMsg += ' with credentials ' + USERNAME + "/" + PASSWORD; | |
| } | |
| app.listen(PORT); | |
| console.log(startupMsg + " ..."); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment