-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
77 lines (62 loc) · 1.79 KB
/
index.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
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
'use strict';
const basicAuth = require('basic-auth');
function unauthorized(res, realm) {
const _realm = realm || 'Authorization Required';
res.set('WWW-Authenticate', `Basic realm=${_realm}`);
return res.sendStatus(401);
};
function isPromiseLike(obj) {
return obj && typeof obj.then === 'function';
}
function isValidUser(user, username, password) {
return !(!user || user.name !== username || user.pass !== password);
}
function createMiddleware(username, password, realm) {
const _realm = typeof username === 'function'
? password
: realm;
return function basicAuthMiddleware(req, res, next) {
const user = basicAuth(req);
if (!user) {
return unauthorized(res, realm);
}
let authorized = null;
if (typeof username === 'function') {
const checkFn = username;
try {
authorized = checkFn(user.name, user.pass, function checkFnCallback(err, authentified) {
if (err) {
return next(err);
}
if (authentified) {
return next();
}
return unauthorized(res, _realm);
});
} catch(err) {
next(err);
}
} else if (Array.isArray(username)) {
authorized = username.some(([username, password]) => isValidUser(user, username, password));
} else {
authorized = isValidUser(user, username, password);
}
if (isPromiseLike(authorized)) {
return authorized
.then(function(authorized) {
if (authorized === true) {
return next();
}
return unauthorized(res, _realm);
})
.catch(next);
}
if (authorized === false) {
return unauthorized(res, _realm);
}
if (authorized === true) {
return next();
}
};
};
module.exports = createMiddleware;