Using the Express framework for node.js, I\'m trying to serve up static files contained in a directory while also putting basic authentication on it. When I do so, I am prompted
The answer:
var express = require("express")
var ss = require("serve-static")
var ba = require("basic-auth")
var app = express()
app.use("/", ss(__dirname + "/public"))
app.use(entry)
app.use("/privatesite", ss(__dirname + "/private"))
app.listen(4000)
function entry(req, res, next) {
var objUser = ba(req)
if (objUser === undefined || objUser.name !== "john" || objUser.pass !== "1234") {
res.set("WWW-Authenticate", "Basic realm=Authorization Required")
res.status(401).end()
} else { next() }
}
The 1st app.use() line offers the content of "public" folder in x.x.x.x:4000 ("/" route) to all visitors. The 3rd app.use() line offers the content of "private" folder in x.x.x.x:4000/privatesite ("/privatesite" route) only to user "john" because this line is written after 2nd app.use() line, which loads the authentication middleware. This authentication middleware uses "basic-auth" component, which returns an object with the name and pass written by client. If it is not "john" and "1234", server returns a 401 page; if it is, continue (thanks to next()) to 3rd app.use() line