Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 36 additions & 1 deletion cf-worker/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,35 @@ function newUrl(urlStr) {
}
}

// begin authentication
const AUTH_ENABLE = false // whether enable authentication
const userpass = {"user" : "pass"} // key-value pair of username and password
const AUTH_REALM = "Authentication required" // string to display

function checkAuthRequest(request) {
const header = new Map(request.headers)
//console.log(header)
if (!header.has("authorization")) {
return false
}
const auth = header.get("authorization").split(' ')
if (auth.length != 2 || auth[0] != "Basic") {
return false
}
return checkAuth(auth[1], userpass);
}

function checkAuth(str, userpass) {
const decoded = atob(str).split(":")
if (decoded.length != 2) {
return false
} else {
const user = decoded[0]
const pass = decoded[1]
return userpass[user] && userpass[user] == pass
}
}
// end authentication

addEventListener('fetch', e => {
const ret = fetchHandler(e)
Expand All @@ -53,6 +82,12 @@ addEventListener('fetch', e => {
* @param {FetchEvent} e
*/
async function fetchHandler(e) {
// begin authentication
if (AUTH_ENABLE && !checkAuthRequest(e.request)) {
return new Response("", {status: 401, headers: {"WWW-Authenticate": 'Basic realm="' + AUTH_REALM + '"'}})
}
// end authentication

const req = e.request
const urlStr = req.url
const urlObj = new URL(urlStr)
Expand Down Expand Up @@ -287,4 +322,4 @@ async function parseYtVideoRedir(urlObj, newLen, res) {
return null
}
return urlObj
}
}