-
-
Save bainternet/2caf936380789378d159afad16471ab2 to your computer and use it in GitHub Desktop.
CloudFlare Workers
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
// Thanks to https://phiilu.medium.com/password-protect-your-vercel-site-with-cloudflare-workers-a0070357a005 | |
// See: https://brawl.vivaldi.net/?p=208 | |
const CREDENTIALS_REGEXP = /^ *[Bb][Aa][Ss][Ii][Cc] +([\w+./~-]+=*) *$/; | |
const USER_PASS_REGEXP = /^([^:]*):(.*)$/; | |
class Credentials { | |
constructor(name, pass) { | |
this.name = name; | |
this.pass = pass; | |
} | |
} | |
const parseAuthHeader = (string) => { | |
if (typeof string !== 'string') { | |
return null; | |
} | |
// parse header | |
const match = CREDENTIALS_REGEXP.exec(string); | |
if (!match) { | |
return null; | |
} | |
// decode user pass | |
const userPass = USER_PASS_REGEXP.exec(atob(match[1])); | |
if (!userPass) { | |
return null; | |
} | |
// return credentials object | |
return new Credentials(userPass[1], userPass[2]); | |
}; | |
const unauthorizedResponse = (body) => | |
new Response(body, { | |
status: 401, | |
headers: { | |
'WWW-Authenticate': 'Basic realm="docs"', | |
}, | |
}); | |
export async function onRequest({ env, next, request }) { | |
const { pathname } = new URL(request.url); | |
if (pathname === '/favicon.ico' || pathname === '/robots.txt') { | |
return next(); | |
} | |
const credentials = parseAuthHeader(request.headers.get('Authorization')); | |
if ( | |
!credentials || | |
credentials.name !== env.USER || | |
credentials.pass !== env.PASS | |
) { | |
return unauthorizedResponse('Unauthorized'); | |
} | |
return next(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment