From 284499745a25528757d31b3dd903b354e1b53e8e Mon Sep 17 00:00:00 2001 From: Chever John Date: Tue, 30 Jun 2026 20:35:08 +0800 Subject: [PATCH] fix: ensure auth token is present before upload request Add proactive token refresh when getAccessToken() returns null, plus 401 retry logic. The in-memory token can be null if it expired between page load and upload attempt. Co-Authored-By: Claude --- src/api/common.ts | 37 ++++++++++++++++++++++++++++--------- 1 file changed, 28 insertions(+), 9 deletions(-) diff --git a/src/api/common.ts b/src/api/common.ts index fafd917..77ff869 100644 --- a/src/api/common.ts +++ b/src/api/common.ts @@ -53,16 +53,35 @@ export const commonApi = { formData.append('bucket', bucket); formData.append('path_prefix', pathPrefix); - const token = getAccessToken(); - const headers: Record = {}; - if (token) headers['Authorization'] = `Bearer ${token}`; + if (!getAccessToken()) { + const { authApi } = await import('./auth'); + try { await authApi.refresh(); } catch { /* will fail on upload */ } + } - const res = await fetch('/api/v1/common/upload', { - method: 'POST', - headers, - body: formData, - credentials: 'include', - }); + const doUpload = async () => { + const token = getAccessToken(); + const headers: Record = {}; + if (token) headers['Authorization'] = `Bearer ${token}`; + + return fetch('/api/v1/common/upload', { + method: 'POST', + headers, + body: formData, + credentials: 'include', + }); + }; + + let res = await doUpload(); + + if (res.status === 401) { + const { authApi } = await import('./auth'); + try { + await authApi.refresh(); + } catch { + throw new Error('auth expired'); + } + res = await doUpload(); + } if (!res.ok) { throw new Error('upload failed');