-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
45 lines (41 loc) · 1.15 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
const EventEmitter = require('events')
class BasicAuth extends EventEmitter {
description () {
return 'Password-protect a server using Basic Authentication.'
}
optionDefinitions () {
return [
{
name: 'auth.user',
type: String,
description: 'Basic authentication username'
},
{
name: 'auth.pass',
type: String,
description: 'Basic authentication password'
}
]
}
middleware (options) {
if (options.authUser && options.authPass) {
this.emit('verbose', 'basic-auth.config', { authUser: options.authUser, authPass: '**********' })
}
return (ctx, next) => {
if (options.authUser && options.authPass) {
const auth = require('basic-auth')
const credentials = auth(ctx)
if (!(credentials && credentials.name === options.authUser && credentials.pass === options.authPass)) {
ctx.status = 401
ctx.set('WWW-Authenticate', 'Basic realm="example"')
ctx.body = 'Access denied'
} else {
return next()
}
} else {
return next()
}
}
}
}
module.exports = BasicAuth