|
1 | 1 | const auth = require('basic-auth') |
2 | 2 | const assert = require('assert') |
3 | 3 |
|
| 4 | +function ensureFunction(option, defaultValue) { |
| 5 | + if(option == undefined) |
| 6 | + return function() { return defaultValue } |
| 7 | + |
| 8 | + if(typeof option != 'function') |
| 9 | + return function() { return option } |
| 10 | + |
| 11 | + return option |
| 12 | +} |
| 13 | + |
4 | 14 | function buildMiddleware(options) { |
5 | 15 | var challenge = options.challenge != undefined ? !!options.challenge : false |
6 | 16 | var users = options.users || {} |
7 | 17 | var authorizer = options.authorizer || staticUsersAuthorizer |
8 | 18 | var isAsync = options.authorizeAsync != undefined ? !!options.authorizeAsync : false |
9 | | - var getResponseBody = options.unauthorizedResponse |
| 19 | + var getResponseBody = ensureFunction(options.unauthorizedResponse, '') |
| 20 | + var realm = ensureFunction(options.realm) |
10 | 21 |
|
11 | | - if(!getResponseBody) |
12 | | - getResponseBody = function() { return '' } |
13 | | - else if(typeof getResponseBody != 'function') |
14 | | - getResponseBody = function() { return options.unauthorizedResponse } |
15 | | - |
16 | | - assert(typeof getResponseBody == 'function', 'Expected a string or function for the unauthorizedResponse option') |
17 | 22 | assert(typeof users == 'object', 'Expected an object for the basic auth users, found ' + typeof users + ' instead') |
18 | 23 | assert(typeof authorizer == 'function', 'Expected a function for the basic auth authorizer, found ' + typeof authorizer + ' instead') |
19 | 24 |
|
@@ -44,9 +49,15 @@ function buildMiddleware(options) { |
44 | 49 | return next() |
45 | 50 |
|
46 | 51 | function unauthorized() { |
47 | | - //TODO: Allow to set realm for the challenge |
48 | | - if(challenge) |
49 | | - res.set('WWW-Authenticate', 'Basic') |
| 52 | + if(challenge) { |
| 53 | + var challengeString = 'Basic' |
| 54 | + var realmName = realm(req) |
| 55 | + |
| 56 | + if(realmName) |
| 57 | + challengeString += ' realm="' + realmName + '"' |
| 58 | + |
| 59 | + res.set('WWW-Authenticate', challengeString) |
| 60 | + } |
50 | 61 |
|
51 | 62 | //TODO: Allow response body to be JSON (maybe autodetect?) |
52 | 63 | const response = getResponseBody(req) |
|
0 commit comments