From 4f83e5ebd4c7a24bb8ff9b79d2b915c23d403dbd Mon Sep 17 00:00:00 2001 From: Pratyush-Panda-2006 Date: Sun, 2 Aug 2026 22:25:38 +0530 Subject: [PATCH] fix(auth): implement token expiration handling and graceful re-authentication (fix #1052) --- frontend/src/context/AuthContext.jsx | 16 ++++++++++++++-- frontend/src/lib/axios.js | 7 ++++--- 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/frontend/src/context/AuthContext.jsx b/frontend/src/context/AuthContext.jsx index d944d6c..18f9b7c 100644 --- a/frontend/src/context/AuthContext.jsx +++ b/frontend/src/context/AuthContext.jsx @@ -12,14 +12,12 @@ export const AuthProvider = ({ children }) => { const hasChecked = useRef(false); useEffect(() => { - if (hasChecked.current) return; hasChecked.current = true; const checkAuth = async () => { try { const response = await api.get("/auth/me"); - if (response.data.user) { setUser(response.data.user); } else { @@ -36,6 +34,20 @@ export const AuthProvider = ({ children }) => { checkAuth(); }, []); + useEffect(() => { + const handleUnauthorized = () => { + setUser((prevUser) => { + if (prevUser) { + toast.error("Session expired. Please login again."); + } + return null; + }); + }; + + window.addEventListener("auth:unauthorized", handleUnauthorized); + return () => window.removeEventListener("auth:unauthorized", handleUnauthorized); + }, []); + const register = async (userData) => { try { const response = await api.post("/auth/register", userData); diff --git a/frontend/src/lib/axios.js b/frontend/src/lib/axios.js index efc358c..55c1f50 100644 --- a/frontend/src/lib/axios.js +++ b/frontend/src/lib/axios.js @@ -14,12 +14,13 @@ api.interceptors.response.use( (response) => response, (error) => { if (error.response?.status === 401) { - console.log("Unauthorized - but not redirecting immediately"); - + const url = error.config?.url || ""; + if (!url.includes("/auth/login") && !url.includes("/auth/register")) { + window.dispatchEvent(new CustomEvent("auth:unauthorized")); + } } return Promise.reject(error); } ); export default api; -