80 lines
2.3 KiB
TypeScript
80 lines
2.3 KiB
TypeScript
import type { FormSubmitEvent } from "@nuxt/ui";
|
|
|
|
const isRedirecting = ref(false);
|
|
|
|
export function useAuthConnexion() {
|
|
const { isLoggedIn } = useAuth();
|
|
const toast = useToast();
|
|
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<AuthLoginForm>, redirect?: string) {
|
|
try {
|
|
const { success, message } = await $fetch("/api/login", { method: "POST", body });
|
|
if (!success) {
|
|
throw new Error(message);
|
|
}
|
|
toast.add({
|
|
title: "Connexion réussie",
|
|
color: "success",
|
|
description: message,
|
|
duration: 3000,
|
|
});
|
|
await redirectTo(redirect);
|
|
}
|
|
catch (error) {
|
|
console.log(error);
|
|
toast.add({
|
|
title: "Erreur de connexion",
|
|
color: "error",
|
|
description: error instanceof Error ? error.message : "Une erreur est survenue lors de la connexion.",
|
|
duration: 5000,
|
|
});
|
|
}
|
|
}
|
|
|
|
// 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.");
|
|
}
|
|
toast.add({
|
|
title: "Déconnexion réussie",
|
|
color: "success",
|
|
description: "Vous avez été déconnecté avec succès.",
|
|
duration: 3000,
|
|
});
|
|
await redirectTo(redirect);
|
|
}
|
|
catch (error) {
|
|
console.log(error);
|
|
toast.add({
|
|
title: "Erreur de déconnexion",
|
|
color: "error",
|
|
description: error instanceof Error ? error.message : "Une erreur est survenue lors de la déconnexion.",
|
|
duration: 5000,
|
|
});
|
|
}
|
|
}
|
|
|
|
// Dynamic connexion link
|
|
const connexionButton = computed(() => ({
|
|
label: isLoggedIn.value ? "Déconnexion" : "Connexion",
|
|
icon: isLoggedIn.value ? "i-lucide-log-out" : "i-lucide-log-in",
|
|
to: "/connexion",
|
|
}));
|
|
|
|
return { isRedirecting, login, logout, connexionButton };
|
|
}
|