From 596c9d8879d2196c06d15726354d5ee402324b44 Mon Sep 17 00:00:00 2001 From: Guillermo Perez Date: Mon, 24 Jun 2024 15:59:19 +0200 Subject: [PATCH] Update pw protection script (#52) * Update script from source (Cloudflare) --- tinlake-ui-password-CF/password.js | 103 ++++++++++++++--------------- 1 file changed, 51 insertions(+), 52 deletions(-) diff --git a/tinlake-ui-password-CF/password.js b/tinlake-ui-password-CF/password.js index 538a80fd..2d177f0c 100644 --- a/tinlake-ui-password-CF/password.js +++ b/tinlake-ui-password-CF/password.js @@ -1,58 +1,57 @@ -// This script is deployed as a Cloudflare Worker under the Centrifuge account. -// It handles password-based authentication for protected resources, setting a secure cookie upon successful authentication. - addEventListener('fetch', event => { - event.respondWith(handleRequest(event.request)) - }) - - async function handleRequest(request) { - const AUTH_PASS = 'Centrifuge'; // Define the password here - - // Check for authentication cookie - const cookie = request.headers.get('Cookie'); - if (cookie && cookie.includes('auth=valid')) { - return fetch(request); - } - - const url = new URL(request.url); - const params = new URLSearchParams(url.search); - const password = params.get('password'); - + event.respondWith(handleRequest(event.request)) +}) + +async function handleRequest(request) { + const AUTH_PASS = 'Centrifuge'; // Define the password here + + // Check for authentication cookie + const cookie = request.headers.get('Cookie'); + if (cookie && cookie.includes('auth=valid')) { + return fetch(request); + } + + if (request.method === "POST") { + const formData = await request.clone().formData(); + const password = formData.get('password'); + if (password === AUTH_PASS) { - const originalResponse = await fetch(request); - const newHeaders = new Headers(originalResponse.headers); - newHeaders.append('Set-Cookie', `auth=valid; Max-Age=86400; Path=/; HttpOnly; Secure; SameSite=Strict`); - return new Response(originalResponse.body, { - status: originalResponse.status, - statusText: originalResponse.statusText, + const redirectUrl = new URL(request.url); + const newHeaders = new Headers({ + 'Set-Cookie': `auth=valid; Max-Age=86400; Path=/; HttpOnly; Secure; SameSite=Strict`, + 'Location': redirectUrl.toString() // Redirect to the same URL or to a specific path + }); + return new Response(null, { + status: 302, headers: newHeaders }); - } else if (password) { + } else { return new Response('Invalid password', { status: 403 }); } - - // Serve the styled HTML form for password input - return new Response(` - - - - - -
- - -
- - - `, { - headers: { - 'Content-Type': 'text/html', - }, - status: 401 - }); - } \ No newline at end of file + } + + // Serve the styled HTML form for password input + return new Response(` + + + + + +
+ + +
+ + + `, { + headers: { + 'Content-Type': 'text/html', + }, + status: 401 + }); +} \ No newline at end of file