From 86cb0f4aa3223e32363d118a1bb2008ebe53d082 Mon Sep 17 00:00:00 2001 From: CzBiX Date: Tue, 25 May 2021 00:59:13 +0800 Subject: [PATCH] Add auth index only option --- src/auth/config.js | 2 ++ src/index.js | 36 +++++++++++++++++++----------------- 2 files changed, 21 insertions(+), 17 deletions(-) diff --git a/src/auth/config.js b/src/auth/config.js index fa816a31..6cb97110 100644 --- a/src/auth/config.js +++ b/src/auth/config.js @@ -3,10 +3,12 @@ * Enabled by default, you need to set PASSWORD secret using `wrangler secret put AUTH_PASSWORD` * * AUTH_ENABLED `false` to disable it + * AUTH_INDEX_ONLY `true` will require password at dir index page only * NAME user name * ENABLE_PATHS enable protection on specific folders/files */ export const AUTH_ENABLED = true +export const AUTH_INDEX_ONLY = false export const NAME = 'guest' export const ENABLE_PATHS = ['/🌞 Private folder/Private folder'] diff --git a/src/index.js b/src/index.js index 4aec948e..9d0c96cc 100644 --- a/src/index.js +++ b/src/index.js @@ -1,5 +1,5 @@ import config from './config/default' -import { AUTH_ENABLED, NAME, ENABLE_PATHS } from './auth/config' +import { AUTH_ENABLED, AUTH_INDEX_ONLY, NAME, ENABLE_PATHS } from './auth/config' import { parseAuthHeader, unauthorizedResponse } from './auth/credentials' import { getAccessToken, getSiteID } from './auth/onedrive' import { handleFile, handleUpload } from './files/load' @@ -12,28 +12,30 @@ addEventListener('fetch', event => { }) async function handle(request) { - if (AUTH_ENABLED === false) { - return handleRequest(request) - } + while (true) { + if (!AUTH_ENABLED) { + break + } - if (AUTH_ENABLED === true) { const pathname = decodeURIComponent(new URL(request.url).pathname).toLowerCase() - const privatePaths = ENABLE_PATHS.map(i => i.toLowerCase()) - - if (privatePaths.filter(p => pathname.toLowerCase().startsWith(p)).length > 0 || /__Lock__/gi.test(pathname)) { - const credentials = parseAuthHeader(request.headers.get('Authorization')) + if (AUTH_INDEX_ONLY && !pathname.endsWith('/')) { + break + } - if (!credentials || credentials.name !== NAME || credentials.pass !== AUTH_PASSWORD) { - return unauthorizedResponse('Unauthorized') - } + const privatePaths = ENABLE_PATHS.map(i => i.toLowerCase()) + if (!privatePaths.some(p => pathname.toLowerCase().startsWith(p)) && !/__Lock__/gi.test(pathname)) { + break + } - return handleRequest(request) - } else { - return handleRequest(request) + const credentials = parseAuthHeader(request.headers.get('Authorization')) + if (credentials && credentials.name === NAME && credentials.pass === AUTH_PASSWORD) { + break } - } else { - console.info('Auth error unexpected.') + + return unauthorizedResponse('Unauthorized') } + + return handleRequest(request) } // Cloudflare cache instance