-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathindex.js
50 lines (42 loc) · 967 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
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
'use strict';
/**
* Module dependencies.
*/
const auth = require('basic-auth');
const compare = require('tsscmp');
/**
* Return basic auth middleware with
* the given options:
*
* - `name` username
* - `pass` password
* - `realm` realm
*
* @param {Object} opts
* @return {GeneratorFunction}
* @api public
*/
module.exports = function(opts){
opts = opts || {};
if (!opts.name && !opts.pass)
throw new Error('Basic auth `name` and/or `pass` is required');
if (!opts.realm) opts.realm = 'Secure Area';
return function basicAuth(ctx, next) {
const user = auth(ctx);
if (
!user ||
(opts.name && !compare(opts.name, user.name)) ||
(opts.pass && !compare(opts.pass, user.pass))
)
return ctx.throw(
401,
null,
{
headers: {
'WWW-Authenticate': 'Basic realm="' + opts.realm.replace(/"/g, '\\"') + '"'
}
}
);
return next();
};
};