generated from pascalmartineau/wp-skeleton
59 lines
1.7 KiB
TypeScript
59 lines
1.7 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: args }: FormSubmitEvent<LoginOutput>) {
|
|
try {
|
|
const { data, errors } = await useGraphqlMutation("login", args);
|
|
if (errors.length || !data.login) {
|
|
console.error(errors);
|
|
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 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 };
|
|
}
|