refactor: Creation d'un provider et d'un systeme de middleware

This commit is contained in:
Luc SORIGNET
2025-02-22 13:05:01 +01:00
parent c861239d48
commit 508847940c
18 changed files with 218 additions and 69 deletions

View File

@ -8,8 +8,12 @@ const CsrfContext = createContext();
export const CsrfProvider = ({ children }) => {
const [csrfToken, setCsrfTokenState] = useState('');
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
// Éviter les appels multiples si le token existe déjà
if (csrfToken) return;
fetch(`${BE_AUTH_CSRF_URL}`, {
method: 'GET',
credentials: 'include' // Inclut les cookies dans la requête
@ -24,16 +28,23 @@ export const CsrfProvider = ({ children }) => {
})
.catch(error => {
console.error('Error fetching CSRF token:', error);
})
.finally(() => {
setIsLoading(false);
});
}, []);
}, []); // Dépendance vide pour n'exécuter qu'une seule fois
return (
<CsrfContext.Provider value={csrfToken}>
{children}
{!isLoading && children}
</CsrfContext.Provider>
);
};
export const useCsrfToken = () => {
return useContext(CsrfContext);
const context = useContext(CsrfContext);
if (context === undefined) {
throw new Error('useCsrfToken must be used within a CsrfProvider');
}
return context;
};