Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions frontend/src/context/AuthContext.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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);
Expand Down
7 changes: 4 additions & 3 deletions frontend/src/lib/axios.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Loading