From a08adf3c03cb61495e235f782c4e7d919ddc9fdd Mon Sep 17 00:00:00 2001 From: Toby Date: Thu, 24 Jul 2025 21:56:26 +0200 Subject: [PATCH] add basic helper function --- src/index.ts | 2 ++ tests/index.spec.ts | 15 +++++++++++++++ 2 files changed, 17 insertions(+) diff --git a/src/index.ts b/src/index.ts index a663322..1b0328e 100644 --- a/src/index.ts +++ b/src/index.ts @@ -52,6 +52,7 @@ export type RouterRequest = ReqExt & { formData(): Promise blob(): Promise bearer(): string | undefined + basic(): [string, string] cf?: IncomingRequestCfProperties } @@ -396,6 +397,7 @@ export class Router { formData: async (): Promise => buffer.formData ? buffer.formData : buffer.formData = await request.clone().formData(), blob: async (): Promise => buffer.blob ? buffer.blob : buffer.blob = await request.clone().blob(), bearer: () => request.headers.get('Authorization')?.replace(/^[Bb]earer\s/, '').trim(), + basic: () => (atob(request.headers.get('Authorization')?.replace(/^[Bb]asic\s/, '').trim() ?? '') || undefined)?.split(':') } as RouterRequest if (this.corsEnabled && req.method === 'OPTIONS') { diff --git a/tests/index.spec.ts b/tests/index.spec.ts index 3063526..d6aa9cf 100644 --- a/tests/index.spec.ts +++ b/tests/index.spec.ts @@ -261,6 +261,21 @@ describe('Router', () => { expect(await response.text()).toBe(testToken) }) + + test('basic', async () => { + const router = new Router() + const testCredentials = ['user', 'password'] + const testBasicAuth = btoa(testCredentials.join(':')) + const testRequest = new Request('https://example.com/', { headers: { 'Authorization': `Basic ${testBasicAuth}` }}) + + router.get('/', ({ req }) => Response.json(req.basic())) + + const response = await router.handle(testRequest, {}) + + expect(response.status).toEqual(200) + + expect(await response.json()).toMatchObject(testCredentials) + }) }) describe('Middleware', () => {