mirror of
https://git.v0id.ovh/n3wt-innov/n3wt-school.git
synced 2026-01-29 07:53:23 +00:00
refactor: Creation d'un provider et d'un systeme de middleware
This commit is contained in:
@ -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;
|
||||
};
|
||||
Reference in New Issue
Block a user