1 | var middleware = require('./middleware')
|
2 | var urlUtils = require('url')
|
3 |
|
4 | function encodeBasicAuthorizationHeader (s) {
|
5 | return 'Basic ' + Buffer.from(s).toString('base64')
|
6 | }
|
7 |
|
8 | module.exports = middleware('basicAuth', function (request, next) {
|
9 | function basicAuthorizationHeader () {
|
10 | if (request.options.basicAuth) {
|
11 | var username = request.options.basicAuth.username || ''
|
12 | var password = request.options.basicAuth.password || ''
|
13 |
|
14 | return encodeBasicAuthorizationHeader(username.replace(/:/g, '') + ':' + password)
|
15 | } else {
|
16 | var url = urlUtils.parse(request.url)
|
17 | if (url.auth) {
|
18 | return encodeBasicAuthorizationHeader(url.auth)
|
19 | }
|
20 | }
|
21 | }
|
22 |
|
23 | var header = basicAuthorizationHeader()
|
24 | if (header) {
|
25 | request.headers.authorization = header
|
26 | }
|
27 |
|
28 | return next()
|
29 | })
|