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 <noreply@anthropic.com>
This commit is contained in:
Chever John 2026-06-30 20:35:08 +08:00
parent 1b506edfbf
commit 284499745a
No known key found for this signature in database
GPG Key ID: 2894D52ED1211DF0

View File

@ -53,16 +53,35 @@ export const commonApi = {
formData.append('bucket', bucket);
formData.append('path_prefix', pathPrefix);
const token = getAccessToken();
const headers: Record<string, string> = {};
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<string, string> = {};
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');