diff --git a/lib/auth.js b/lib/auth.js new file mode 100644 index 0000000..440bba1 --- /dev/null +++ b/lib/auth.js @@ -0,0 +1,40 @@ +module.exports = function (app, user, password) { + app.use(function* (next) { + const challenge = `Basic realm="Node File Manager"` + let authorization = this.header['authorization'] + if (authorization != null && authorization.slice(0, 6) === 'Basic ') { + authorization = new Buffer(authorization.slice(6), 'base64').toString('utf8') + const splitIndex = authorization.indexOf(':') + if (splitIndex > -1) { + const user = authorization.slice(0, splitIndex) + const password = authorization.slice(splitIndex + 1) + this.request.auth = { + user: user, + password: password + } + } + } + + yield next + + if (this.request.auth == null) { + this.status = 401 + this.response.set('WWW-Authenticate', challenge) + } + }) + + app.use(function* (next) { + if (!this.request.auth) { + this.body = 'Please log in.' + return // 401 response + } + + if (this.request.auth.user !== user || this.request.auth.password !== password) { + this.body = 'Invalid user.' + delete this.request.auth + return // 401 response + } + + yield next + }) +} \ No newline at end of file diff --git a/lib/index.js b/lib/index.js index 94c6a8f..001a4f1 100644 --- a/lib/index.js +++ b/lib/index.js @@ -10,7 +10,7 @@ var koaStatic = require('koa-static'); // Config var argv = require('optimist') .usage([ - 'USAGE: $0 [-p ] [-d ]'] + 'USAGE: $0 [-p ] [-d ] [--user ] [--password ]'] ) .option('port', { alias: 'p', @@ -29,6 +29,12 @@ var argv = require('optimist') alias: 'h', description: "Display This Help Message" }) + .option('user', { + description: "Username for basic http auth" + }) + .option('password', { + description: "Password for basic http auth" + }) .argv; if (argv.help) { @@ -41,6 +47,11 @@ if (argv.version) { process.exit(0); } +if ((argv.user && !argv.password) || (argv.password && !argv.user)) { + console.log('Both username and password are required to enable http auth') + process.exit(0); +} + global.C = { data: { root: argv.directory || path.dirname('.') @@ -58,6 +69,12 @@ var startServer = function (app, port) { }; var app = koa(); + +if (argv.user && argv.password) { + var enableAuth = require('./auth') + enableAuth(app, argv.user, argv.password) +} + app.proxy = true; app.use(Tools.handelError); app.use(Tools.realIp);