Skip to content

Commit

Permalink
Implemented timeout and default error page
Browse files Browse the repository at this point in the history
  • Loading branch information
Carlos Rodriguez committed Jul 21, 2012
1 parent 4009f8d commit fbb23a5
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 4 deletions.
2 changes: 1 addition & 1 deletion examples/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ var http = require('http')
realm: 'My secret server',
accounts: ['foo:1234']
})
, port = 3000
, port = 3001
;

http.createServer(function(req, res) {
Expand Down
19 changes: 16 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,27 @@

module.exports = function(options) {
if (typeof options.timeout === 'undefined') {
options.timeout = 2000;
}
function accessDenied(res) {
res.writeHead(401, {'WWW-Authenticate': 'Basic realm="' + options.realm + '"'});
res.write(options.errorContent || '<html><head><title>Access Denied</title></head><body><h1>Access Denied</h1></body></html>');
res.end();
}
return function tinyAuth(req, res, next) {
if (req.headers['authorization'] && req.headers['authorization'].indexOf('Basic ') === 0) {
if (options.accounts.indexOf(new Buffer(req.headers['authorization'].split(' ')[1], 'base64').toString()) !== -1) {
next();
return;
}
else {
// A timeout makes it slightly harder to brute-force.
setTimeout(accessDenied.bind(null, res), options.timeout);
}
}
else {
// Immediate prompt.
accessDenied(res);
}

res.writeHead(401, {'WWW-Authenticate': 'Basic realm="' + options.realm + '"'});
res.end();
};
};

0 comments on commit fbb23a5

Please sign in to comment.