Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add auth #1

Merged
merged 3 commits into from
Oct 30, 2023
Merged
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
42 changes: 42 additions & 0 deletions functions/_middleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// https://developers.cloudflare.com/workers/examples/basic-auth

export async function onRequest(context) {
const { request, env } = context

const auth = request.headers.get('Authorization')
if (auth) {
const [scheme, encoded] = auth.split(' ')

if (!encoded || scheme !== 'Basic') {
return new Response('Malformed authorization header.', { status: 400 })
}

const buffer = Uint8Array.from(atob(encoded), (character) =>
character.charCodeAt(0)
)
const decoded = new TextDecoder().decode(buffer).normalize()

const index = decoded.indexOf(':')

// eslint-disable-next-line no-control-regex
if (index === -1 || /[\0-\x1F\x7F]/.test(decoded)) {
return new Response('Invalid authorization value.', { status: 400 })
}

const user = decoded.substring(0, index)
const pass = decoded.substring(index + 1)

if (user !== env.BASIC_USER || pass !== env.BASIC_PASSWORD) {
return new Response('Invalid username or password.', { status: 401 })
}

return context.next()
}

return new Response('Login required', {
status: 401,
headers: {
'WWW-Authenticate': 'Basic realm="gsod", charset="UTF-8"'
}
})
}