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
25 changes: 25 additions & 0 deletions frontend/src/api.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,20 @@
// API INDEX
const BASE = (import.meta.env.VITE_API_URL || '').replace(/\/$/, '');
export const COOKIE_MISSING_EVENT = 'bcan:cookie-missing';
let hasDispatchedCookieMissingEvent = false;

function notifyCookieMissing(path: string): void {
if (hasDispatchedCookieMissingEvent || typeof window === 'undefined') {
return;
}

hasDispatchedCookieMissingEvent = true;
window.dispatchEvent(
new CustomEvent(COOKIE_MISSING_EVENT, {
detail: { path },
})
);
}

type ApiInit = RequestInit & { __retry?: boolean };
let refreshInFlight: Promise<boolean> | null = null;
Expand Down Expand Up @@ -31,6 +46,16 @@ export async function api(
const cleanPath = path.startsWith('/') ? path : `/${path}`;
const url = `${BASE}${cleanPath}`;

const response = await fetch(url, {
credentials: 'include',
...init,
});

if (response.status === 401) {
notifyCookieMissing(cleanPath);
}

return response;
const typedInit = init as ApiInit;
const { __retry, ...fetchInit } = typedInit;

Expand Down
42 changes: 40 additions & 2 deletions frontend/src/context/auth/authContext.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { useContext, createContext, ReactNode, useEffect, useRef } from 'react';
import { useContext, createContext, ReactNode, useEffect, useRef, useState } from 'react';
import { getAppStore } from '../../external/bcanSatchel/store';
import { setAuthState, logoutUser } from '../../external/bcanSatchel/actions';
import { observer } from 'mobx-react-lite';
import { User } from '../../../../middle-layer/types/User';
import { api } from '../../api';
import { api, COOKIE_MISSING_EVENT } from '../../api';
import { fetchUsers } from '../../main-page/users/UserActions.ts';
import Button from '../../components/Button';


/**
Expand Down Expand Up @@ -32,6 +33,7 @@ export const useAuthContext = () => {
export const AuthProvider = observer(({ children }: { children: ReactNode }) => {
const store = getAppStore();
const logoutTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const [showCookieErrorPrompt, setShowCookieErrorPrompt] = useState(false);
// Auto-logout timeout duration (in milliseconds)
// 8 hours = 8 * 60 * 60 * 1000
const SESSION_TIMEOUT = 8 * 60 * 60 * 1000;
Expand Down Expand Up @@ -135,6 +137,26 @@ export const AuthProvider = observer(({ children }: { children: ReactNode }) =>
};
}, [store.isAuthenticated]);

useEffect(() => {
const onCookieMissing = () => {
if (store.isAuthenticated) {
setShowCookieErrorPrompt(true);
}
};

window.addEventListener(COOKIE_MISSING_EVENT, onCookieMissing);

return () => {
window.removeEventListener(COOKIE_MISSING_EVENT, onCookieMissing);
};
}, [store.isAuthenticated]);

useEffect(() => {
if (!store.isAuthenticated && showCookieErrorPrompt) {
setShowCookieErrorPrompt(false);
}
}, [showCookieErrorPrompt, store.isAuthenticated]);

/** Restore user session on refresh */
// useEffect(() => {
// api('/auth/session')
Expand All @@ -154,6 +176,22 @@ export const AuthProvider = observer(({ children }: { children: ReactNode }) =>
}}
>
{children}
{showCookieErrorPrompt && (
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
<div className="bg-white rounded-md px-8 py-6 max-w-md mx-4 text-center">
<h3 className="text-xl font-bold mb-2">Internal Error</h3>
<p className="mb-4">
An internal error occurred and your session could not be verified.
Please log out and log back in.
</p>
<Button
text="Logout"
onClick={logout}
className="text-white bg-primary-900 mx-auto"
/>
</div>
</div>
)}
</AuthContext.Provider>
);
});
Loading