import type { FormSubmitEvent } from "@nuxt/ui"; const isRedirecting = ref(false); export function useAuthConnexion() { const { fetch: refreshUserSession } = useUserSession(); const routeRedirect = useRoute().query.redirect as string || undefined; // Helper: Redirect after login / logout async function redirectTo(to: string | undefined) { isRedirecting.value = true; await delay(1000); await refreshUserSession(); await navigateTo(to || routeRedirect || "/"); } // Login async function login({ data: body }: FormSubmitEvent, redirect?: string) { try { const { success, message } = await $fetch("/api/login", { method: "POST", body }); if (!success) { throw new Error(message); } await redirectTo(redirect); } catch (error) { console.log(error); } } // Logout async function logout(redirect?: string) { try { const result = await $fetch("/api/logout", { method: "POST" }); if (!result.success) { throw new Error("Échec de la déconnexion."); } await redirectTo(redirect); } catch (error) { console.log(error); } } return { isRedirecting, login, logout }; }