From 47dfb8797fbbceecf95dd703acf73ec07157bf64 Mon Sep 17 00:00:00 2001 From: Prateek Shourya Date: Wed, 12 Jun 2024 19:18:48 +0530 Subject: [PATCH] [WEB-1564] chore: add interceptor to handle 401 errors and redirect users to login page. (#4788) --- web/core/services/api.service.ts | 14 ++++++++++++++ web/core/services/user.service.ts | 3 ++- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/web/core/services/api.service.ts b/web/core/services/api.service.ts index c80f71017..0886fe9b0 100644 --- a/web/core/services/api.service.ts +++ b/web/core/services/api.service.ts @@ -11,6 +11,20 @@ export abstract class APIService { baseURL, withCredentials: true, }); + + this.setupInterceptors(); + } + + private setupInterceptors() { + this.axiosInstance.interceptors.response.use( + (response) => response, + (error) => { + if (error.response && error.response.status === 401) { + window.location.reload(); + } + return Promise.reject(error); + } + ); } get(url: string, params = {}, config = {}) { diff --git a/web/core/services/user.service.ts b/web/core/services/user.service.ts index 9202da9fe..6c75de94c 100644 --- a/web/core/services/user.service.ts +++ b/web/core/services/user.service.ts @@ -46,7 +46,8 @@ export class UserService extends APIService { } async currentUser(): Promise { - return this.get("/api/users/me/") + // Using validateStatus: null to bypass interceptors for unauthorized errors. + return this.get("/api/users/me/", { validateStatus: null }) .then((response) => response?.data) .catch((error) => { throw error?.response;