http-auth
Version:
Node.js package for HTTP basic and digest access authentication.
111 lines (100 loc) • 3.02 kB
JavaScript
// Generated by CoffeeScript 1.8.0
(function() {
var Base, fs;
fs = require('fs');
Base = (function() {
function Base(options, checker) {
this.options = options;
this.checker = checker;
if (!this.options.msg401) {
this.options.msg401 = "401 Unauthorized";
}
if (!this.options.msg407) {
this.options.msg407 = "407 Proxy authentication required";
}
if (!this.options.contentType) {
this.options.contentType = "text/plain";
}
if (!this.options.realm) {
this.options.realm = "Users";
}
this.options.users = [];
if (!this.checker && this.options.file) {
this.loadUsers();
}
}
Base.prototype.isAuthenticated = function(req, callback) {
var clientOptions, error, header, searching;
try {
if (this.proxy) {
header = req.headers["proxy-authorization"];
} else {
header = req.headers["authorization"];
}
if (header) {
clientOptions = this.parseAuthorization(header);
if (clientOptions) {
searching = true;
this.findUser(req, clientOptions, (function(_this) {
return function(result) {
return callback.apply(_this, [result]);
};
})(this));
}
}
} catch (_error) {
error = _error;
console.error(error.message);
}
if (!searching) {
return callback.apply(this, [{}]);
}
};
Base.prototype.loadUsers = function() {
var line, lines, _i, _len, _results;
lines = ((fs.readFileSync(this.options.file, 'UTF-8')).replace(/\r\n/g, "\n")).split("\n");
_results = [];
for (_i = 0, _len = lines.length; _i < _len; _i++) {
line = lines[_i];
if (line) {
_results.push(this.processLine(line));
} else {
_results.push(void 0);
}
}
return _results;
};
Base.prototype.ask = function(res, result) {
var header;
header = this.generateHeader(result);
res.setHeader("Content-Type", this.options.contentType);
if (this.proxy) {
res.setHeader("Proxy-Authenticate", header);
res.writeHead(407);
return res.end(this.options.msg407);
} else {
res.setHeader("WWW-Authenticate", header);
res.writeHead(401);
return res.end(this.options.msg401);
}
};
Base.prototype.check = function(req, res, callback) {
return this.isAuthenticated(req, (function(_this) {
return function(result) {
if (!result.user) {
return _this.ask(res, result);
} else {
if (!_this.options.skipUser) {
req.user = result.user;
}
if (callback) {
return callback.apply(_this, [req, res]);
}
}
};
})(this));
};
return Base;
})();
module.exports = Base;
}).call(this);