/** * Import types from Nadal. */ import type { SignUpRequestPayload } from '@kira-dancer/nadal' import { useUserStore, useModalsStore } from '#lib/stores' import type { UserStore, UserLoginRequest, BaseNadalResponse, AppCookies, } from '#lib/types' import { useGameToast, useNadal, usePromotion, useResetStore, } from '#lib/composables' import { setIsLogged } from '#lib/utils' import { useNuxtApp } from 'nuxt/app' import { AppStorageEnum } from '#lib/enums' /** * Custom hook for handling authentication logic. * @returns An object containing authentication methods. * @namespace * @namespace */ export const useAuth = () => { /** * Nadal auth instance. */ const nuxtApp = useNuxtApp() const $appCookies = nuxtApp.$appCookies as AppCookies const { auth } = useNadal() const store = useUserStore() const resetStore = useResetStore() const { fetchUserPromotion } = usePromotion() const { resetToasts } = useGameToast() const modalsStore = useModalsStore() /** * Handles the login process. * @param {UserLoginRequest} requestUser - The user login details * @returns A promise that resolves when the login is successful. */ const onLogin = async (requestUser: UserLoginRequest): Promise => { const data = await auth.signIn(requestUser) if (data) { $appCookies.token.value = data.token $appCookies.gpToken.value = data.gptoken store.setUser(data) setIsLogged(true) window.dispatchEvent(new Event(AppStorageEnum.Storage)) fetchUserPromotion() } } /** * Handles the logout process. * @returns A promise that resolves when the logout is successful. */ const onLogout = async (): Promise => { try { const data = await auth.signOut() return data } finally { resetStore.resetAll() store.resetUser() resetToasts() $appCookies.token.value = null $appCookies.gpToken.value = null } } /** * Handles the registration process. * * SignUpRequestPayload type is imported from the Nadal module. * @param {SignUpRequestPayload} data - The user registration details. * @returns A promise that resolves when the registration is successful. */ const onRegister = async (data: SignUpRequestPayload): Promise => { const response = await auth.signUp(data) store.setUser(response) $appCookies.token.value = response.token $appCookies.gpToken.value = response.gptoken window.dispatchEvent(new Event(AppStorageEnum.Storage)) } /** * Opens the authentication modal. */ const openAuthModal = () => { modalsStore.setOpenAuthModal(true) } /** * Opens the login expired modal. */ const openExpiredModal = () => { modalsStore.setOpenExpireModal(true) } return { openExpiredModal, openAuthModal, onLogin, onLogout, onRegister, } }