|
| 1 | +const auth = require('./proxy-auth') |
| 2 | +const assert = require('assert') |
| 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 | + |
| 14 | +function buildMiddleware(options) { |
| 15 | + var challenge = options.challenge != undefined ? !!options.challenge : false |
| 16 | + var users = options.users || {} |
| 17 | + var authorizer = options.authorizer || staticUsersAuthorizer |
| 18 | + var isAsync = options.authorizeAsync != undefined ? !!options.authorizeAsync : false |
| 19 | + var getResponseBody = ensureFunction(options.unauthorizedResponse, '') |
| 20 | + var realm = ensureFunction(options.realm) |
| 21 | + |
| 22 | + assert(typeof users == 'object', 'Expected an object for the basic auth users, found ' + typeof users + ' instead') |
| 23 | + assert(typeof authorizer == 'function', 'Expected a function for the basic auth authorizer, found ' + typeof authorizer + ' instead') |
| 24 | + |
| 25 | + function staticUsersAuthorizer(username, password) { |
| 26 | + for(var i in users) |
| 27 | + if(username == i && password == users[i]) |
| 28 | + return true |
| 29 | + |
| 30 | + return false |
| 31 | + } |
| 32 | + |
| 33 | + return function authMiddleware(req, res, next) { |
| 34 | + if (req.method === 'OPTIONS') { |
| 35 | + next(); |
| 36 | + return; |
| 37 | + } |
| 38 | + var authentication = auth(req) |
| 39 | + |
| 40 | + if(!authentication) |
| 41 | + return unauthorized() |
| 42 | + |
| 43 | + req.auth = { |
| 44 | + user: authentication.name, |
| 45 | + password: authentication.pass |
| 46 | + } |
| 47 | + |
| 48 | + if(isAsync) |
| 49 | + return authorizer(authentication.name, authentication.pass, authorizerCallback) |
| 50 | + else if(!authorizer(authentication.name, authentication.pass)) |
| 51 | + return unauthorized() |
| 52 | + |
| 53 | + return next() |
| 54 | + |
| 55 | + function unauthorized() { |
| 56 | + if(challenge) { |
| 57 | + var challengeString = 'Basic' |
| 58 | + var realmName = realm(req) |
| 59 | + |
| 60 | + if(realmName) |
| 61 | + challengeString += ' realm="' + realmName + '"' |
| 62 | + |
| 63 | + res.set('WWW-Authenticate', challengeString) |
| 64 | + } |
| 65 | + |
| 66 | + const response = getResponseBody(req) |
| 67 | + |
| 68 | + if(typeof response == 'string') |
| 69 | + return res.status(401).send(response) |
| 70 | + |
| 71 | + return res.status(401).json(response) |
| 72 | + } |
| 73 | + |
| 74 | + function authorizerCallback(err, approved) { |
| 75 | + assert.ifError(err) |
| 76 | + |
| 77 | + if(approved) |
| 78 | + return next() |
| 79 | + |
| 80 | + return unauthorized() |
| 81 | + } |
| 82 | + } |
| 83 | +} |
| 84 | + |
| 85 | +module.exports = buildMiddleware |
0 commit comments