Skip to content

Commit bdefea0

Browse files
author
Leon Strauss
committed
added asynch authorizers
1 parent 99e59c8 commit bdefea0

1 file changed

Lines changed: 24 additions & 6 deletions

File tree

index.js

Lines changed: 24 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ function buildMiddleware(options) {
55
var challenge = options.challenge != undefined ? !!options.challenge : true;
66
var users = options.users || {};
77
var authorizer = options.authorizer || staticUsersAuthorizer;
8+
var isAsync = options.authorizeAsync != undefined ? !!options.authorizeAsync : false;
89

910
assert(typeof users == 'object', 'Expected an object for the basic auth users, found ' + typeof users + ' instead');
1011
assert(typeof authorizer == 'function', 'Expected a function for the basic auth authorizer, found ' + typeof authorizer + ' instead');
@@ -20,7 +21,22 @@ function buildMiddleware(options) {
2021
return function authMiddleware(req, res, next) {
2122
var authentication = auth(req);
2223

23-
if(!authentication || !authorizer(authentication.name, authentication.pass)) {
24+
if(!authentication)
25+
return unauthorized();
26+
27+
if(isAsync)
28+
return authorizer(authentication.name, authentication.pass, authorizerCallback);
29+
else if(!authorizer(authentication.name, authentication.pass))
30+
return unauthorized();
31+
32+
req.auth = {
33+
user: authentication.name,
34+
password: authentication.pass
35+
};
36+
37+
next();
38+
39+
function unauthorized() {
2440
res.status(401);
2541

2642
if(challenge)
@@ -29,12 +45,14 @@ function buildMiddleware(options) {
2945
return res.send('');
3046
}
3147

32-
req.auth = {
33-
user: authentication.name,
34-
password: authentication.pass
35-
};
48+
function authorizerCallback(err, approved) {
49+
assert.ifError(err);
3650

37-
next();
51+
if(approved)
52+
return next();
53+
54+
return unauthorized();
55+
}
3856
};
3957
}
4058

0 commit comments

Comments
 (0)