80 lines
2 KiB
TypeScript
80 lines
2 KiB
TypeScript
import { DEFAULT_LOCALE } from '@appConstants';
|
|
import { useLocaleRedirect } from '@composables/languages';
|
|
import { useNotification } from '@composables/notification';
|
|
import { useUserBaseData } from '@composables/user';
|
|
import { LOGIN } from '@graphql/mutations/auth';
|
|
import type { ILoginResponse } from '@types';
|
|
|
|
export function useLogin() {
|
|
const { t } = useI18n();
|
|
const userStore = useUserStore();
|
|
const localePath = useLocalePath();
|
|
const { $appHelpers } = useNuxtApp();
|
|
|
|
const { checkAndRedirect } = useLocaleRedirect();
|
|
|
|
const cookieRefresh = useCookie($appHelpers.COOKIES_REFRESH_TOKEN_KEY, {
|
|
default: () => '',
|
|
path: '/',
|
|
});
|
|
const cookieAccess = useCookie($appHelpers.COOKIES_ACCESS_TOKEN_KEY, {
|
|
default: () => '',
|
|
path: '/',
|
|
});
|
|
const cookieLocale = useCookie($appHelpers.COOKIES_LOCALE_KEY, {
|
|
default: () => DEFAULT_LOCALE,
|
|
path: '/',
|
|
});
|
|
|
|
const { mutate, loading, error } = useMutation<ILoginResponse>(LOGIN);
|
|
|
|
async function login(email: string, password: string, isStayLogin: boolean) {
|
|
const result = await mutate({
|
|
email,
|
|
password,
|
|
});
|
|
const authData = result?.data?.obtainJwtToken;
|
|
if (!authData) return;
|
|
|
|
if (isStayLogin && authData.refreshToken) {
|
|
cookieRefresh.value = authData.refreshToken;
|
|
}
|
|
|
|
userStore.setUser(authData.user);
|
|
cookieAccess.value = authData.accessToken;
|
|
|
|
navigateTo(localePath('/'));
|
|
|
|
useNotification({
|
|
message: t('popup.success.login'),
|
|
type: 'success',
|
|
});
|
|
|
|
if (authData.user.language !== cookieLocale.value) {
|
|
await checkAndRedirect(authData.user.language);
|
|
}
|
|
|
|
await useUserBaseData(authData.user.email);
|
|
}
|
|
|
|
watch(error, (err) => {
|
|
if (!err) return;
|
|
console.error('useLogin error:', err);
|
|
let message = t('popup.errors.defaultError');
|
|
if (isGraphQLError(err)) {
|
|
message = err.graphQLErrors?.[0]?.message || message;
|
|
} else {
|
|
message = err.message;
|
|
}
|
|
useNotification({
|
|
message,
|
|
type: 'error',
|
|
title: t('popup.errors.main'),
|
|
});
|
|
});
|
|
|
|
return {
|
|
loading,
|
|
login,
|
|
};
|
|
}
|