Created
March 12, 2015 10:17
-
-
Save emilbayes/b219c78a07d8ec26dcf4 to your computer and use it in GitHub Desktop.
Minimal password protected server
This file contains 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
{ | |
"name": "minimal-protected-server", | |
"version": "0.0.0", | |
"description": "Minimal password protected server", | |
"main": "server.js", | |
"dependencies": { | |
"basic": "0.0.3", | |
"st": "^0.5.3" | |
} | |
} |
This file contains 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
'use strict'; | |
//http is already a web framework | |
var http = require('http'); | |
var path = require('path'); | |
//Basic building blocks to Basic Auth and static file serving | |
var basic = require('basic'); | |
var st = require('st'); | |
//Read which port to listen on | |
var PORT = process.argv[2] || process.env.PORT || 8080; | |
//Check Basic Auth credentials | |
var auth = basic(function(username, password, callback) { | |
if(username === 'kongfu' && password === 'fighter') | |
return callback(null); | |
return callback(new Error('Access Denied')); | |
}); | |
//Set up the static file reader | |
var staticServe = st({ | |
path: path.join(__dirname, 'dist'), | |
index: 'index.html', | |
passthrough: true //Allows us to react to errors, ie. serve an error page | |
}); | |
//Prebound logging function | |
var log = console.log.bind(console, '%s\t%j', new Date().toISOString()); | |
var server = http.createServer(); | |
//Handle each request stream | |
server.on('request', function(req, res) { | |
log({message: 'Requested', data: {path: req.url}}); | |
//Do post-response logging | |
res.on('finish', function() { | |
log({message: 'Responded', data: {path: req.url, status: res.statusCode, size: res.getHeader('Content-length')}}); | |
}); | |
//Check credentials | |
auth(req, res, function(err) { | |
if(err) { | |
res.statusCode = 401; | |
res.setHeader('WWW-Authenticate', 'Basic realm="Unauthorized"'); | |
return res.end(); | |
} | |
staticServe(req, res, function() { | |
//If the file wasn't found we will serve index.html | |
req.sturl = '/index.html'; | |
staticServe(req, res); | |
}); | |
}); | |
}); | |
//Start listening on the socket | |
server.listen(PORT, function() { | |
log({message: 'Server listening on', data: {port: PORT}}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment