Created
December 31, 2020 05:57
-
-
Save TakuroFukamizu/cba0178bf2e31aa3596e070fb6a08d0b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
// Configure authentication | |
const authUser = 'user'; | |
const authPass = 'pass'; | |
exports.handler = async (event) => { | |
// Get request and request headers | |
const request = event.Records[0].cf.request; | |
const headers = request.headers; | |
// Resolve path index.html | |
let urlItems = /^(.*)\/(\?.*|#.*|$)/.exec(request.uri); | |
// Replace uri | |
if (urlItems != null) { | |
request.uri = `${urlItems[1]}/index.html${urlItems[2]}`; | |
} | |
const ignore_list = [ | |
/\/manifest\.json$/, /\/service-worker\.js$/, /\/precache-manifest\..*\.js$/, /\/graphql\/?$/ | |
]; | |
if (ignore_list.reduce((prev, ignore) => prev | ignore.test(request.uri), false)) { // PWA need manifest file always. | |
return request; | |
} | |
// Construct the Basic Auth string | |
const authString = 'Basic ' + new Buffer(authUser + ':' + authPass).toString('base64'); | |
// Require Basic authentication | |
if (typeof headers.authorization == 'undefined' || headers.authorization[0].value != authString) { | |
const body = 'Unauthorized'; | |
return { | |
status: '401', | |
statusDescription: 'Unauthorized', | |
body: body, | |
headers: { | |
'www-authenticate': [{key: 'WWW-Authenticate', value:'Basic'}] | |
}, | |
}; | |
} | |
else { | |
// Continue request processing if authentication passed | |
return request; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment