generated from pascalmartineau/wp-skeleton
49 lines
1.4 KiB
TypeScript
49 lines
1.4 KiB
TypeScript
import type { FormSubmitEvent } from "@nuxt/ui";
|
|
import * as z from "zod";
|
|
|
|
const loginSchema = z.object({
|
|
email: z.email("Courriel invalide"),
|
|
password: z.string("Veuillez saisir votre mot de passe"),
|
|
});
|
|
type LoginSchema = z.infer<typeof loginSchema>;
|
|
|
|
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,
|
|
},
|
|
];
|
|
|
|
export function useLogin() {
|
|
const toast = useToast();
|
|
const redirect = useRoute().query.redirect as string || "/";
|
|
const router = useRouter();
|
|
const { fetch: refreshUserSession } = useUserSession();
|
|
|
|
async function onLoginSubmit({ data }: FormSubmitEvent<LoginSchema>) {
|
|
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" });
|
|
}
|
|
}
|
|
|
|
return { loginSchema, loginFields, onLoginSubmit };
|
|
}
|