Skip to content

Instantly share code, notes, and snippets.

@bainternet
Forked from Brawl345/basic-auth-[[path]].js
Created May 23, 2022 06:54
Show Gist options
  • Save bainternet/2caf936380789378d159afad16471ab2 to your computer and use it in GitHub Desktop.
Save bainternet/2caf936380789378d159afad16471ab2 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