-
Notifications
You must be signed in to change notification settings - Fork 2
/
basic-auth.js
52 lines (41 loc) · 1.58 KB
/
basic-auth.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
module.exports = function (callback, realm) {
if (!callback || typeof callback != 'function') {
throw new Error('You must provide a function ' +
'callback as the first parameter');
}
realm = realm ? realm : 'Authorization required.';
function unauthorized(res, sendResponse) {
res.statusCode = 401;
res.setHeader('WWW-Authenticate', 'Basic realm="' + realm + '"');
if (sendResponse) {
res.end('Unauthorized');
}
}
return function(req, res, next) {
req.requireAuthorization = function(req, res, next) {
var authorization = req.headers.authorization;
if (req.remoteUser) return next();
if (!authorization) return unauthorized(res, true);
var parts = authorization.split(' ');
var scheme = parts[0];
if ('Basic' != scheme) {
return next(new Error('Authorization header ' +
'does not have the correct scheme. \'Basic\' ' +
'scheme was expected.'));
}
var _credentials = new Buffer(parts[1], 'base64').toString().split(':');
var credentials = { username: _credentials[0],
password: _credentials[1] };
callback(credentials, req, res, function(err) {
if (err) {
unauthorized(res);
next(err);
return;
}
req.remoteUser = credentials.username;
next();
});
};
next();
};
};