Send the auth token on every API call; build against the API's own domain
Seven call sites used fetch() directly instead of the api client in src/api/client.js, so they sent no Authorization header. Four of them hit endpoints the backend guards with a permission, and every one of those returned 401 for any signed-in user: AdminPage /api/admin/training/upload-dataset (upload_train_test) AdminPage /api/admin/training/allocate-discounts (allocate_discounts) UserPage /api/user/products/add (add_product) UserPage /api/user/products/upload-file (upload_batch_products) The remaining three hit public GETs and worked, but bypassed VITE_API_BASE_URL and the central 401 handler just the same. Route all seven through the client and add the endpoints it was missing. Multipart uploads still need a raw fetch, because the browser has to set its own Content-Type to carry the boundary, so that is now one upload() helper that attaches the auth header and routes 401s to the logout handler rather than three copies that did neither. handleAllocateDiscounts only acted on res.ok, so a 401 or 403 left the panel looking idle with no indication that nothing had been allocated. It surfaces the error now. Take VITE_API_BASE_URL as a Docker build arg. The app is served from catalogue.nearle.ai.in and the API from mcp.catalogue.nearle.ai.in, and Vite inlines env vars at build time, so setting this on the running container does nothing - it has to reach npm run build. Defaults to empty, which keeps requests relative for the same-origin nginx proxy. Also revoke the object URL after the sample-CSV download. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -88,6 +88,49 @@ async function request(path, options = {}) {
|
||||
return res.json();
|
||||
}
|
||||
|
||||
/**
|
||||
* POST a file as multipart/form-data.
|
||||
*
|
||||
* Deliberately not routed through request(): the browser must set its own
|
||||
* Content-Type so it can append the multipart boundary, and request()'s JSON
|
||||
* default would corrupt the body. Everything else request() does still has to
|
||||
* happen by hand here - most importantly the Authorization header, whose
|
||||
* absence is exactly what used to make every upload in the app 401.
|
||||
*/
|
||||
async function upload(path, file, { fieldName = 'file' } = {}) {
|
||||
const formData = new FormData();
|
||||
formData.append(fieldName, file);
|
||||
|
||||
let res;
|
||||
try {
|
||||
res = await fetch(`${BASE}${path}`, {
|
||||
method: 'POST',
|
||||
headers: authHeaders(),
|
||||
body: formData,
|
||||
});
|
||||
} catch {
|
||||
throw new ApiError(
|
||||
`Could not reach the API at ${BASE || '(same origin)'}${path}. Is the backend running ` +
|
||||
`and reachable?`,
|
||||
0
|
||||
);
|
||||
}
|
||||
|
||||
if (!res.ok) {
|
||||
let detail = `Upload failed (${res.status})`;
|
||||
try {
|
||||
const body = await res.json();
|
||||
detail = body.detail || JSON.stringify(body);
|
||||
} catch {
|
||||
/* ignore parse errors, keep generic message */
|
||||
}
|
||||
if (res.status === 401 && onUnauthorized) onUnauthorized(detail);
|
||||
throw new ApiError(detail, res.status);
|
||||
}
|
||||
|
||||
return res.json();
|
||||
}
|
||||
|
||||
function qs(params = {}) {
|
||||
const usp = new URLSearchParams();
|
||||
Object.entries(params).forEach(([k, v]) => {
|
||||
@@ -219,30 +262,33 @@ export const api = {
|
||||
getNutritionEnrichmentStatus: () => request('/api/admin/nutrition-intelligence/status'),
|
||||
|
||||
// --- Excel / CSV Upload API ---
|
||||
// Raw fetch rather than request(): the browser must set its own multipart
|
||||
// Content-Type with the boundary, so the JSON default in request() would
|
||||
// corrupt the body. The auth header still has to be added by hand here.
|
||||
uploadFile: async (tabType, file) => {
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
const res = await fetch(`${BASE}/api/upload/${encodeURIComponent(tabType)}`, {
|
||||
method: 'POST',
|
||||
headers: authHeaders(),
|
||||
body: formData,
|
||||
});
|
||||
if (!res.ok) {
|
||||
let detail = `Upload failed (${res.status})`;
|
||||
try {
|
||||
const body = await res.json();
|
||||
detail = body.detail || JSON.stringify(body);
|
||||
} catch {}
|
||||
if (res.status === 401 && onUnauthorized) onUnauthorized(detail);
|
||||
throw new ApiError(detail, res.status);
|
||||
}
|
||||
return res.json();
|
||||
},
|
||||
uploadFile: (tabType, file) => upload(`/api/upload/${encodeURIComponent(tabType)}`, file),
|
||||
|
||||
getTemplateUrl: (tabType) => `${BASE}/api/upload/template/${encodeURIComponent(tabType)}`,
|
||||
|
||||
// --- Admin: training datasets & discount allocation ---
|
||||
// Guarded by `upload_train_test` / `allocate_discounts` on the server, so
|
||||
// these must carry the bearer token - see app/api/routers/admin_train.py.
|
||||
getProjectDetails: () => request('/api/admin/training/project-details'),
|
||||
|
||||
uploadTrainingDataset: (file) => upload('/api/admin/training/upload-dataset', file),
|
||||
|
||||
allocateDiscounts: ({ rules, store_id = null }) =>
|
||||
request('/api/admin/training/allocate-discounts', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ store_id, rules }),
|
||||
}),
|
||||
|
||||
// --- User workspace: single + batch product entry ---
|
||||
// Guarded by `add_product` / `upload_batch_products` - see
|
||||
// app/api/routers/user_products.py.
|
||||
addUserProduct: (payload) =>
|
||||
request('/api/user/products/add', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(payload),
|
||||
}),
|
||||
|
||||
uploadUserProductsFile: (file) => upload('/api/user/products/upload-file', file),
|
||||
};
|
||||
|
||||
export { ApiError };
|
||||
|
||||
Reference in New Issue
Block a user