Files
cultureat-bak/wp-content/themes/ccat/app/composables/useAuth.ts
Pascal Martineau 346890c088
All checks were successful
Deploy WordPress and Nuxt / deploy (push) Successful in 6m3s
refactor: better project structure
2025-09-17 08:41:42 -04:00

58 lines
1.8 KiB
TypeScript

import type { FormSubmitEvent } from "@nuxt/ui";
export function useAuth() {
const toast = useToast();
const redirect = useRoute().query.redirect as string || "/";
const router = useRouter();
const { fetch: refreshUserSession } = useUserSession();
// Login form
const loginFields = [
{
name: "email",
type: "text" as const,
label: "Courriel",
placeholder: "Entrez votre courriel",
required: true,
}, {
name: "password",
label: "Mot de passe",
type: "password" as const,
placeholder: "Entrez votre mot de passe",
required: true,
},
];
async function onLoginSubmit({ data }: FormSubmitEvent<LoginOutput>) {
try {
const result = await $fetch<{ success: boolean; message?: string }>("/api/login", { method: "POST", body: data });
if (!result.success) {
throw new Error(result.message || "Une erreur est survenue.");
}
await router.push(redirect);
await refreshUserSession();
}
catch (error) {
const message = error instanceof Error ? error.message : "Une erreur est survenue.";
toast.add({ title: "Échec de la connexion", description: message, color: "error" });
}
}
// Logout action
async function onLogoutClick() {
try {
const result = await $fetch("/api/logout", { method: "POST" });
if (!result.success) {
throw new Error("Une erreur est survenue.");
}
await router.push(redirect);
await refreshUserSession();
}
catch (error) {
const message = error instanceof Error ? error.message : "Une erreur est survenue.";
toast.add({ title: "Échec de la déconnexion", description: message, color: "error" });
}
}
return { loginFields, onLoginSubmit, onLogoutClick };
}