From 54c834d2132e42f31575c1915ff9760675bef256 Mon Sep 17 00:00:00 2001 From: SangLv Date: Fri, 18 Aug 2023 18:34:45 +0700 Subject: [PATCH 1/2] navigate login when expried --- frontend/src/utils/axios.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/frontend/src/utils/axios.ts b/frontend/src/utils/axios.ts index f17c7a7f3..a82e87433 100644 --- a/frontend/src/utils/axios.ts +++ b/frontend/src/utils/axios.ts @@ -26,7 +26,10 @@ axios.interceptors.response.use( error.config.headers.Authorization = `Bearer ${access_token}` return axiosLibrary(error.config) } - return Promise.reject(error) + if (error?.response?.status === 400) { + return window.location.href = '/login'; + } + return Promise.reject(error) }, ) From 004d7b0a3fe88bf7177fe4e26024dd0e879433b1 Mon Sep 17 00:00:00 2001 From: SangLv Date: Mon, 21 Aug 2023 14:04:38 +0700 Subject: [PATCH 2/2] fix navigate when 400 refreshToken --- frontend/src/utils/auth/AuthUtils.ts | 11 +++++++++++ frontend/src/utils/axios.ts | 23 ++++++++++++++--------- 2 files changed, 25 insertions(+), 9 deletions(-) diff --git a/frontend/src/utils/auth/AuthUtils.ts b/frontend/src/utils/auth/AuthUtils.ts index 335317aa7..2712bbc3a 100644 --- a/frontend/src/utils/auth/AuthUtils.ts +++ b/frontend/src/utils/auth/AuthUtils.ts @@ -14,6 +14,17 @@ export const getRefreshToken = () => { return localStorage.getItem('refresh_token') } +export const removeRefreshToken = () => { + return localStorage.removeItem('refresh_token') +} + +export const logout = () => { + removeRefreshToken(); + removeToken() + removeExToken(); + window.location.href = '/login' +} + export const removeToken = () => { return localStorage.removeItem('access_token') } diff --git a/frontend/src/utils/axios.ts b/frontend/src/utils/axios.ts index a82e87433..52b66443c 100644 --- a/frontend/src/utils/axios.ts +++ b/frontend/src/utils/axios.ts @@ -1,7 +1,7 @@ import axiosLibrary from 'axios' import { refreshTokenApi } from 'api/auth/Auth' import { BASE_URL } from 'const/API' -import { getExToken, getToken, saveToken } from 'utils/auth/AuthUtils' +import {getExToken, getToken, logout, saveToken} from 'utils/auth/AuthUtils' const axios = axiosLibrary.create({ baseURL: BASE_URL, @@ -21,15 +21,20 @@ axios.interceptors.response.use( async (res) => res, async (error) => { if (error?.response?.status === 401) { - const { access_token } = await refreshTokenApi() - saveToken(access_token) - error.config.headers.Authorization = `Bearer ${access_token}` - return axiosLibrary(error.config) + try { + const { access_token } = await refreshTokenApi() + saveToken(access_token) + error.config.headers.Authorization = `Bearer ${access_token}` + return axiosLibrary(error.config) + } + catch (e: any) { + if (e?.response?.status === 400) { + logout(); + } + throw e; + } } - if (error?.response?.status === 400) { - return window.location.href = '/login'; - } - return Promise.reject(error) + return Promise.reject(error) }, )