import z from "zod"; import type { FormSubmitEvent } from "@nuxt/ui"; export const authLoginFormSchema = z.object({ username: z.email("Courriel invalide"), password: z.string("Veuillez saisir votre mot de passe"), }); export type AuthLoginForm = z.infer; 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 || "/"); isRedirecting.value = false; } // Login const { mutate: loginMutate } = useGraphQLMutation("AuthLogin"); async function login({ data: variables }: FormSubmitEvent, redirect?: string) { try { const { data } = await loginMutate(variables); if (!data?.login) { throw new Error(`Échec de la connexion par mot de passe.`); } 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 }; }