diff --git a/app/lib/api.ts b/app/lib/api.ts index b26b23c..062c434 100644 --- a/app/lib/api.ts +++ b/app/lib/api.ts @@ -39,6 +39,19 @@ class ApiService { this.token = null; } + private handleSessionExpired(message?: string) { + this.clearToken(); + localStorage.removeItem("auth_token"); + localStorage.removeItem("auth_user"); + try { + sessionStorage.setItem("sessionExpired", "1"); + } catch {} + if (message) { + toast.error(message); + } + window.location.href = "/login"; + } + private async request( endpoint: string, options: RequestInit = {}, @@ -66,6 +79,11 @@ class ApiService { const response = await fetch(url, config); const data: ApiResponse = await response.json(); + if (data.errorCode === 301) { + this.handleSessionExpired("نشست شما منقضی شده است. لطفا دوباره وارد شوید."); + throw new Error(data.message || "Session expired"); + } + // Handle different response states if (!response.ok) { throw new Error( @@ -91,13 +109,7 @@ class ApiService { // Handle authentication errors if (error instanceof Error && error.message.includes("401")) { - this.clearToken(); - localStorage.removeItem("auth_token"); - localStorage.removeItem("auth_user"); - try { - sessionStorage.setItem("sessionExpired", "1"); - } catch {} - window.location.href = "/login"; + this.handleSessionExpired(); throw error; } @@ -128,6 +140,11 @@ class ApiService { const response = await fetch(fullUrl, config); const apiData: ApiResponse = await response.json(); + if (apiData.errorCode === 301) { + this.handleSessionExpired("نشست شما منقضی شده است. لطفا دوباره وارد شوید."); + throw new Error(apiData.message || "Session expired"); + } + if (!response.ok) { throw new Error(apiData?.message || `HTTP error! status: ${response.status}`); }