feat(auth): implement refresh token handling and update login method
This commit is contained in:
@@ -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', 'نشست منقضی شده است');
|
||||
|
||||
Reference in New Issue
Block a user