Last active
September 12, 2017 02:43
-
-
Save chukonu/8bf89e57bf7729f11d43acdbdde862b6 to your computer and use it in GitHub Desktop.
a premature test server for basic authentication
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
const express = require('express') | |
const app = express() | |
const port = 3000 | |
const host = '192.168.10.112' | |
const realm = 'protected' | |
const templ = fillTempl`<html> | |
<head><title>${0}</title></head> | |
<body><h1>${1}</h1></body> | |
</html>` | |
app.get('/', function (req, res) { | |
console.log('hello world') | |
res.send(templ('Hello World', 'Hello World!')) | |
}) | |
app.get('/protected', function (req, res) { | |
let auth = req.headers.authorization | |
// console.log(`Authorization Header: ${auth}`) | |
if (!auth) { | |
raiseAuth(res) | |
return | |
} | |
let plainAuth = decodeAuthHeader(auth) | |
res.send(templ('Authorised', `Authorised to: ${plainAuth}`)) | |
}) | |
app.listen(port, host, function () { | |
console.log(`server listening on ${port}`) | |
}) | |
function raiseAuth(res) { | |
res.setHeader('WWW-Authenticate', `Basic realm="${realm}"`) | |
res.sendStatus(401) | |
} | |
function decodeAuthHeader(authHeader) { | |
let tmp = authHeader.split(' ') | |
let buf = new Buffer(tmp[1], 'base64') | |
return buf.toString() | |
} | |
function fillTempl(strings, ...keys) { | |
return (function (...values) { | |
let dict = values[values.length-1] || {} | |
let result = [strings[0]] | |
keys.forEach(function (key, i) { | |
let value = Number.isInteger(key) ? values[key] : dict[key] | |
result.push(value, strings[i+1]) | |
}) | |
return result.join(' ') | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment