91 lines
2.7 KiB
TypeScript
91 lines
2.7 KiB
TypeScript
import { delay } from "es-toolkit/promise";
|
|
|
|
import type { ButtonProps } from "@nuxt/ui";
|
|
import type { FormSubmitEvent } from "@nuxt/ui";
|
|
|
|
export function useAuthConnexion() {
|
|
const { isLoggedIn } = useAuth();
|
|
const toast = useToast();
|
|
|
|
const defaultRedirect = (useRoute().query.redirect as string) || undefined;
|
|
const isRedirecting = useState("auth.isRedirecting", () => false);
|
|
const { fetch: refreshUserSession } = useUserSession();
|
|
|
|
// Helper: Redirect after login / logout
|
|
async function redirectTo(to: string | undefined) {
|
|
isRedirecting.value = true;
|
|
await delay(1000);
|
|
await refreshUserSession();
|
|
await navigateTo(to || defaultRedirect || "/");
|
|
}
|
|
|
|
/**
|
|
* Attempt login with the provided credentials.
|
|
*
|
|
* @param event The form submit event containing the login credentials.
|
|
* @param redirect Optional URL to redirect to after successful login.
|
|
* @returns A promise that resolves when the login process is complete.
|
|
*/
|
|
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({
|
|
color: "success",
|
|
title: "Connexion réussie",
|
|
description: message,
|
|
});
|
|
|
|
await redirectTo(redirect);
|
|
} catch (error) {
|
|
toast.add({
|
|
color: "error",
|
|
title: "Erreur de connexion",
|
|
description:
|
|
error instanceof Error ? error.message : "Une erreur est survenue lors de la connexion.",
|
|
});
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Logout the current user.
|
|
*
|
|
* @param redirect Optional URL to redirect to after successful logout.
|
|
* @returns A promise that resolves when the logout process is complete.
|
|
*/
|
|
async function logout(redirect?: string) {
|
|
try {
|
|
const { success, message } = await $fetch("/api/logout", { method: "POST" });
|
|
if (!success) throw new Error(message);
|
|
|
|
toast.add({
|
|
color: "success",
|
|
title: "Déconnexion réussie",
|
|
description: message,
|
|
});
|
|
|
|
await redirectTo(redirect);
|
|
} catch (error) {
|
|
toast.add({
|
|
color: "error",
|
|
title: "Erreur de déconnexion",
|
|
description:
|
|
error instanceof Error
|
|
? error.message
|
|
: "Une erreur est survenue lors de la déconnexion.",
|
|
});
|
|
}
|
|
}
|
|
|
|
// Computed property for the connexion button.
|
|
const connexionButton = computed<ButtonProps>(() => ({
|
|
to: "/connexion",
|
|
...(isLoggedIn.value
|
|
? { label: "Déconnexion", icon: "i-lucide-log-out" }
|
|
: { label: "Connexion", icon: "i-lucide-log-in" }),
|
|
}));
|
|
|
|
return { isRedirecting, login, logout, connexionButton };
|
|
}
|