feat(auth): implement refresh token handling and update login method

This commit is contained in:
hamed
2026-06-25 17:37:55 +03:30
parent 694ee28787
commit 9b608aaeac
3 changed files with 62 additions and 7 deletions
+20
View File
@@ -23,9 +23,22 @@ export class ApiError extends Error {
}
}
// چند درخواست همزمان که ۴۰۱ می‌گیرند، فقط یک‌بار refresh را اجرا کنند
let refreshPromise: Promise<string | null> | null = null;
function refreshOnce(): Promise<string | null> {
if (!refreshPromise) {
refreshPromise = useAuthStore.getState().refresh().finally(() => {
refreshPromise = null;
});
}
return refreshPromise;
}
async function request<T>(
path: string,
options: RequestInit = {},
retry = true,
): Promise<T> {
const token = getToken();
const headers: Record<string, string> = {
@@ -38,6 +51,13 @@ async function request<T>(
if (!res.ok) {
if (res.status === 401) {
// تلاش یک‌باره برای تازه‌سازی توکن، سپس اجرای مجدد همان درخواست
if (retry) {
const newToken = await refreshOnce();
if (newToken) {
return request<T>(path, options, false);
}
}
useAuthStore.getState().logout();
window.location.replace('/admin/login');
throw new ApiError(401, 'ERR_UNAUTHORIZED', 'نشست منقضی شده است');