Fix admin login reload loop from stale localStorage tokens.

Clear client tokens on the login page, gate admin pages with shared cookie JWT checks, and clear Secure cookies reliably behind the proxy.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-08-07 11:20:22 +05:00
parent cde790c690
commit 5f2e2f44ca
8 changed files with 324 additions and 72 deletions

View File

@@ -1,8 +1,10 @@
/**
* API client for the bankline admin API.
*
* - Sends the raw JWT access token in the Authorization header
* (the backend middleware expects the bare token, no "Bearer " prefix).
* Auth is cookie-based (HttpOnly admin_access / admin_refresh).
* Requests use credentials: "include". Authorization header is optional
* when a legacy localStorage token is still present.
*
* - Unwraps the response envelope { status, message, code, data }.
* - On 401 tries a one-shot refresh via POST /api/v1/admin/token, then retries.
* - Throws ApiError with a friendly, human-readable message.
@@ -42,6 +44,7 @@
}
}
// Legacy localStorage tokens (optional). Session source of truth is HttpOnly cookies.
const tokens = {
get access() {
return localStorage.getItem(ACCESS_KEY) || "";
@@ -50,8 +53,12 @@
return localStorage.getItem(REFRESH_KEY) || "";
},
set(pair) {
localStorage.setItem(ACCESS_KEY, pair.accessToken || "");
localStorage.setItem(REFRESH_KEY, pair.refreshToken || "");
if (pair && pair.accessToken) {
localStorage.setItem(ACCESS_KEY, pair.accessToken);
}
if (pair && pair.refreshToken) {
localStorage.setItem(REFRESH_KEY, pair.refreshToken);
}
},
clear() {
localStorage.removeItem(ACCESS_KEY);
@@ -78,7 +85,6 @@
return payload.data;
}
if (response.ok && payload && payload.status === undefined) {
// A few endpoints (e.g. JWT middleware errors) don't use the envelope.
return payload;
}
@@ -92,13 +98,14 @@
}
async function refreshTokens() {
const refreshToken = tokens.refresh;
if (!refreshToken) return false;
try {
const body = {};
if (tokens.refresh) body.refreshToken = tokens.refresh;
const response = await fetch("/api/v1/admin/token", {
method: "POST",
credentials: "include",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ refreshToken }),
body: JSON.stringify(body),
});
if (!response.ok) return false;
const payload = await response.json();
@@ -107,7 +114,8 @@
tokens.set(pair);
return true;
}
return false;
// Cookie-only refresh may return a pair; accept any 200 with status true.
return !!(payload && payload.status === true);
} catch (_) {
return false;
}
@@ -147,7 +155,12 @@
let response;
try {
response = await fetch(url, { method, headers, body });
response = await fetch(url, {
method,
headers,
body,
credentials: "include",
});
} catch (_) {
throw new ApiError(
"Network error. Please check your connection and try again.",