Skip to content

Instantly share code, notes, and snippets.

@Brawl345
Created March 25, 2022 17:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Brawl345/c5e126cd47a934caf5d9b914f3584d55 to your computer and use it in GitHub Desktop.
Save Brawl345/c5e126cd47a934caf5d9b914f3584d55 to your computer and use it in GitHub Desktop.
CloudFlare Workers
// 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