diff --git a/src/components/Contexts/UserContext.jsx b/src/components/Contexts/UserContext.jsx index 2146b8a..aad411f 100644 --- a/src/components/Contexts/UserContext.jsx +++ b/src/components/Contexts/UserContext.jsx @@ -11,11 +11,22 @@ export const UserProvider = ({ children }) => { let timer; useEffect(() => { - if (!localStorage) return; - const t = JSON.parse(localStorage.getItem("token")); - if (!t || !t.idToken || !t.idToken.jwtToken) return; - if (!t.idToken.payload || !t.idToken.payload.exp) return; - setToken(t); + try { + if (!localStorage) return; + const t = JSON.parse(localStorage.getItem("token")); + if (!t) return; + if ( + !t.idToken || + !t.idToken.jwtToken || + !t.idToken.payload || + !t.idToken.payload.exp + ) + throw new Error("Invalid token"); + setToken(t); + } catch (e) { + document.location = signOut(); + } + // eslint-disable-next-line react-hooks/exhaustive-deps }, []); useEffect(() => { @@ -33,12 +44,6 @@ export const UserProvider = ({ children }) => { return result; }; - const isError = (resp) => { - if (resp === null) return true; - if (resp && resp.error) return true; - return false; - }; - const startSessionTimer = () => { const duration = 1000 * token.idToken.payload.exp - new Date().getTime(); if (!timer) { @@ -46,8 +51,8 @@ export const UserProvider = ({ children }) => { timer.onMessage(async (e) => { if (e.data === "timeout") { const t = await refreshTokens(); - if (!isError(t)) return; - signOut(); + if (t && !t.error) return; + document.location = signOut(); } }); } @@ -61,17 +66,15 @@ export const UserProvider = ({ children }) => { } = token; const result = await auth.verify(idToken); - if (!result && !result.valid) { + if (!result || !result.valid) { const t = await refreshTokens(); - if (!isError(t)) return; - signOut(); - return; + if (!t || t.error) throw new Error("Unable to refresh token"); } startSessionTimer(); } catch (e) { - signOut(); setError(`Verify error. ${e.message}`); + document.location = signOut(); } }; diff --git a/src/components/Layouts/MenuDrawer.jsx b/src/components/Layouts/MenuDrawer.jsx index 9499a45..0b402be 100644 --- a/src/components/Layouts/MenuDrawer.jsx +++ b/src/components/Layouts/MenuDrawer.jsx @@ -30,6 +30,10 @@ export default function MenuDrawer({ children }) { setOpen(false); }; + const onSignOut = () => { + document.location = signOut(); + }; + return (