UNPKG

814 BJavaScriptView Raw
1var middleware = require('./middleware')
2var urlUtils = require('url')
3
4function encodeBasicAuthorizationHeader (s) {
5 return 'Basic ' + Buffer.from(s).toString('base64')
6}
7
8module.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})