-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathindex.js
More file actions
82 lines (61 loc) · 2.56 KB
/
index.js
File metadata and controls
82 lines (61 loc) · 2.56 KB
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
const auth = require('basic-auth')
const assert = require('assert')
function ensureFunction(option, defaultValue) {
if(option === undefined)
return function() { return defaultValue }
if(typeof option != 'function')
return function() { return option }
return option
}
function buildMiddleware(options) {
var challenge = options.challenge != undefined ? !!options.challenge : false
var users = options.users || {}
var isAsync = options.hasOwnProperty(authorizeAsync) && !!options.authorizeAsync
var getResponseBody = ensureFunction(options.unauthorizedResponse, '')
var realm = ensureFunction(options.realm)
var authorizer
if(options.hasOwnProperty('users')) {
assert(typeof users == 'object', 'Expected an object for the basic auth users, found ' + typeof users + ' instead')
assert(!options.authorizer, 'An users object cannot be combined with a custom authorizer')
authorizer = function(username, password) {
return users.indexOf(username) !== -1 && password === users[username]
}
} else {
assert(typeof options.authorizer == 'function', 'Expected a function for the basic auth authorizer, found ' + typeof authorizer + ' instead')
authorizer = options.authorizer
}
return function authMiddleware(req, res, next) {
var authentication = auth(req)
if(!authentication)
return unauthorized()
req.auth = {
user: authentication.name,
password: authentication.pass
}
var authorized = authorizer(authentication.name, authentication.pass, authorizerCallback)
if(isAsync)
return authorized
return (authorized === true) ? next() : unauthorized()
function unauthorized() {
if(challenge) {
var challengeString = 'Basic'
var realmName = realm(req)
if(realmName)
challengeString += ' realm="' + realmName + '"'
res.set('WWW-Authenticate', challengeString)
}
//TODO: Allow response body to be JSON (maybe autodetect?)
const response = getResponseBody(req)
if(typeof response == 'string')
return res.status(401).send(response)
return res.status(401).json(response)
}
function authorizerCallback(err, approved) {
assert.ifError(err)
if(approved)
return next()
return unauthorized()
}
}
}
module.exports = buildMiddleware