Skip to content

Commit

Permalink
Merge pull request #1 from codeandconspire/add-auth
Browse files Browse the repository at this point in the history
Add auth
  • Loading branch information
tornqvist authored Oct 30, 2023
2 parents cbdd79a + d66c453 commit 9a9cb3a
Showing 1 changed file with 42 additions and 0 deletions.
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"'
}
})
}

0 comments on commit 9a9cb3a

Please sign in to comment.