From efb1b0bfda3421a3d4d81e783f1ccb093b32bbcf Mon Sep 17 00:00:00 2001 From: Alireza Date: Sun, 26 Nov 2023 22:10:16 +0330 Subject: [PATCH] feat: handled refresh token and login token --- frontend/src/pages/Signup/Signup.jsx | 4 ++ .../src/providers/APIProvider/APIProvider.jsx | 71 ++++++++++++++----- .../config-provider/ConfigProvider.jsx | 6 +- 3 files changed, 61 insertions(+), 20 deletions(-) diff --git a/frontend/src/pages/Signup/Signup.jsx b/frontend/src/pages/Signup/Signup.jsx index b6c8fa7..667e530 100644 --- a/frontend/src/pages/Signup/Signup.jsx +++ b/frontend/src/pages/Signup/Signup.jsx @@ -225,6 +225,9 @@ const LoginForm = ({ onSignUpClick }) => { }; const { issueToken, issueTokenResponse } = useAPI(); + const { + setAccessTokenFromLocalStorage + } = useConfig() useEffect(() => { if (issueTokenResponse == null) return; @@ -233,6 +236,7 @@ const LoginForm = ({ onSignUpClick }) => { setOpenToast(true); localStorage['user'] = JSON.stringify(issueTokenResponse.data); + setAccessTokenFromLocalStorage() }, [issueTokenResponse]); const handleClickOnForgotPass = () => { diff --git a/frontend/src/providers/APIProvider/APIProvider.jsx b/frontend/src/providers/APIProvider/APIProvider.jsx index dad3117..427f454 100644 --- a/frontend/src/providers/APIProvider/APIProvider.jsx +++ b/frontend/src/providers/APIProvider/APIProvider.jsx @@ -40,6 +40,32 @@ export function APIProvider({children}) { return `Bearer ${accessToken}` }, [accessToken]) + const refreshAccessToken = useCallback(() => { + const data = { + refresh: refreshToken + } + service.post(`${URL.baseURL}${URL.services.default}${URL.endpoints.token.refresh}`, + data) + .then(response => { + localStorage["user"] = JSON.stringify(response.data) + setAccessTokenFromLocalStorage() + window.location.reload(); + }) + .catch(error => { + if (error == null) + return + + if (error.response.status === 401) { + localStorage['user'] = null + setAccessTokenFromLocalStorage() + } + }) + }, [refreshToken, service, setAccessTokenFromLocalStorage]) + + const updateAccessTokenWithRefreshToken = useCallback(() => { + refreshAccessToken() + }, [refreshAccessToken]) + const removeFromUserCart = useCallback(async ({id, type}) => { let endpoint switch (type) { @@ -63,8 +89,14 @@ export function APIProvider({children}) { }) .catch(error => { setRemoveFromCartResponse(error?.response) + if (!error) + return + + if (error.response.status === 401) { + updateAccessTokenWithRefreshToken() + } }) - }, [getAccessTokenHeader, service]) + }, [getAccessTokenHeader, service, updateAccessTokenWithRefreshToken]) const getUserPresentations = useCallback(async (data) => { await service.get(`${URL.baseURL}${URL.services.default}${URL.endpoints.user.presentation}`, @@ -78,6 +110,12 @@ export function APIProvider({children}) { }) .catch(error => { setUserPresentationsData(error?.response) + if (!error) + return + + if (error.response.status === 401) { + updateAccessTokenWithRefreshToken() + } }) }, [getAccessTokenHeader, service]) @@ -93,6 +131,12 @@ export function APIProvider({children}) { }) .catch(error => { setUserWorkshopsData(error?.response) + if (!error) + return + + if (error.response.status === 401) { + updateAccessTokenWithRefreshToken() + } }) }, [getAccessTokenHeader, service]) @@ -127,12 +171,18 @@ export function APIProvider({children}) { console.log(body) const tokenStr = JSON.parse(localStorage.getItem('user'))['access'] await service.post(`${URL.baseURL}${URL.services.default}${endpoint}`, - body, {headers: {"Authorization" : `Bearer ${tokenStr}`}}) + body, {headers: {"Authorization": `Bearer ${tokenStr}`}}) .then(response => { setAddToCartResponse(response) }) .catch(error => { setAddToCartResponse(error.response) + if (!error) + return + + if (error.response.status === 401) { + updateAccessTokenWithRefreshToken() + } }) }, [service]) @@ -252,23 +302,6 @@ export function APIProvider({children}) { .then(response => setTeachersData(response.data)) }, [currentYear, service]) - const refreshAccessToken = useCallback(() => { - const data = { - refresh: refreshToken - } - service.post(`${URL.baseURL}${URL.services.default}${URL.endpoints.token.refresh}`, - data) - .then(response => { - localStorage["user"] = JSON.stringify(response.data) - setAccessTokenFromLocalStorage() - window.location.reload(); - }) - }, [refreshToken, service, setAccessTokenFromLocalStorage]) - - const updateAccessTokenWithRefreshToken = useCallback(() => { - refreshAccessToken() - }, [refreshAccessToken]) - useEffect(() => { console.log(refreshToken) diff --git a/frontend/src/providers/config-provider/ConfigProvider.jsx b/frontend/src/providers/config-provider/ConfigProvider.jsx index 41aba36..b79e26a 100644 --- a/frontend/src/providers/config-provider/ConfigProvider.jsx +++ b/frontend/src/providers/config-provider/ConfigProvider.jsx @@ -9,7 +9,8 @@ export function ConfigProvider({children}) { const [refreshToken, setRefreshToken] = useState() const setAccessTokenFromLocalStorage = useCallback(() => { - const tokens = JSON.parse(localStorage["user"] ?? "{}") + const lsItem = localStorage["user"] + const tokens = JSON.parse(lsItem !== 'null' ? lsItem : "{}") if (tokens.access != null) { setAccessToken(tokens.access) if (tokens.refresh) { @@ -18,6 +19,9 @@ export function ConfigProvider({children}) { tokens.refresh = refreshToken localStorage["user"] = JSON.stringify(tokens) } + } else { + setAccessToken(null) + setRefreshToken(null) } }, [refreshToken])