-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
25 lines (25 loc) · 805 Bytes
/
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
/**
* [function BasicAuth Middleware]
* @docs http://www.ietf.org/rfc/rfc2617.txt
* @param {[type]} username [description]
* @param {[type]} password [description]
* @param {[type]} realm [description]
* @return {[type]} [description]
*/
module.exports = ({
realm,
username,
password,
auth = ((user, pass) => user === username && pass === password)
}) => {
return async (req, res, next) => {
const authorization = (req.headers['authorization'] || '').split(' ')[1];
const [user, pass] = Buffer.from(authorization, 'base64').toString().split(':');
const ok = await auth(user, pass);
if (ok) return next();
res.writeHead(401, {
'WWW-Authenticate': 'Basic' + (realm ? (' realm="' + realm + '"') : '')
});
res.end('401 Unauthorized');
};
};