Add Telegram Mini App login flow
This commit is contained in:
@@ -6,6 +6,7 @@ import {
|
||||
VerifyLoginCodeDocument,
|
||||
} from '~/composables/graphql/generated';
|
||||
import { useMessengerStart } from '~/composables/useMessengerStart';
|
||||
import { useTelegramMiniApp } from '~/composables/useTelegramMiniApp';
|
||||
|
||||
const config = useRuntimeConfig();
|
||||
const route = useRoute();
|
||||
@@ -30,19 +31,31 @@ const requestCodeMutation = useMutation(RequestLoginCodeDocument, { throws: 'nev
|
||||
const verifyCodeMutation = useMutation(VerifyLoginCodeDocument, { throws: 'never' });
|
||||
const consumeLoginTokenMutation = useMutation(ConsumeLoginTokenDocument, { throws: 'never' });
|
||||
const { openMessengerBot, pendingChannel } = useMessengerStart();
|
||||
const { isAvailable: isTelegramMiniApp, initData: telegramMiniAppInitData, displayName: telegramMiniAppDisplayName } = useTelegramMiniApp();
|
||||
|
||||
const telegramBotUrl = computed(() => config.public.telegramBotUrl || '');
|
||||
const maxBotUrl = computed(() => config.public.maxBotUrl || '');
|
||||
|
||||
const normalizedEmail = computed(() => email.value.trim().toLowerCase());
|
||||
const isEmailReady = computed(() => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(normalizedEmail.value));
|
||||
const nextPath = computed(() =>
|
||||
typeof route.query.next === 'string' && route.query.next.startsWith('/')
|
||||
? route.query.next
|
||||
: '',
|
||||
);
|
||||
const telegramMiniAppMode = ref<'idle' | 'checking' | 'authenticated' | 'needs_email'>('idle');
|
||||
|
||||
async function finalizeSession(accessToken: string) {
|
||||
authCookie.value = accessToken;
|
||||
}
|
||||
|
||||
async function navigateAfterLogin(user: { company?: { id: string } | null }) {
|
||||
if (!user.company?.id) {
|
||||
async function navigateAfterLogin(user: { company?: { id: string } | null; companyId?: string | null }) {
|
||||
if (nextPath.value) {
|
||||
await navigateTo(nextPath.value);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!user.company?.id && !user.companyId) {
|
||||
await navigateTo('/profile');
|
||||
return;
|
||||
}
|
||||
@@ -63,6 +76,9 @@ function normalizeApolloErrorMessage(message: string) {
|
||||
if (message.includes('User for this destination was not found.')) {
|
||||
return 'Пользователь с таким e-mail не найден. Вход доступен только для созданных аккаунтов.';
|
||||
}
|
||||
if (message.includes('Telegram initData')) {
|
||||
return 'Не получилось проверить Telegram Mini App. Откройте кабинет из Telegram заново.';
|
||||
}
|
||||
return message;
|
||||
}
|
||||
|
||||
@@ -143,6 +159,7 @@ async function verifyCode() {
|
||||
}
|
||||
|
||||
await finalizeSession(payload.accessToken);
|
||||
await connectTelegramMiniApp();
|
||||
await navigateAfterLogin(payload.user);
|
||||
}
|
||||
|
||||
@@ -166,6 +183,67 @@ async function consumeLoginToken(loginToken: string) {
|
||||
await navigateAfterLogin(payload.user);
|
||||
}
|
||||
|
||||
async function connectTelegramMiniApp() {
|
||||
if (!isTelegramMiniApp.value || !telegramMiniAppInitData.value) {
|
||||
return;
|
||||
}
|
||||
if (telegramMiniAppMode.value === 'authenticated') {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await $fetch('/api/auth/telegram-mini-app/connect', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
initData: telegramMiniAppInitData.value,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('telegram mini app connect failed', error);
|
||||
}
|
||||
}
|
||||
|
||||
async function tryTelegramMiniAppLogin() {
|
||||
if (!isTelegramMiniApp.value || !telegramMiniAppInitData.value) {
|
||||
return;
|
||||
}
|
||||
|
||||
telegramMiniAppMode.value = 'checking';
|
||||
|
||||
try {
|
||||
const payload = await $fetch<{
|
||||
ok: true;
|
||||
authenticated: boolean;
|
||||
accessToken?: string;
|
||||
user?: { company?: { id: string } | null; companyId?: string | null };
|
||||
telegramUser?: { displayName?: string };
|
||||
}>('/api/auth/telegram-mini-app/session', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
initData: telegramMiniAppInitData.value,
|
||||
},
|
||||
});
|
||||
|
||||
if (payload.authenticated && payload.accessToken && payload.user) {
|
||||
telegramMiniAppMode.value = 'authenticated';
|
||||
await finalizeSession(payload.accessToken);
|
||||
await navigateAfterLogin(payload.user);
|
||||
return;
|
||||
}
|
||||
|
||||
telegramMiniAppMode.value = 'needs_email';
|
||||
feedback.value = payload.telegramUser?.displayName
|
||||
? `${payload.telegramUser.displayName}, введите рабочий e-mail. После входа мы привяжем этот Telegram к вашему кабинету.`
|
||||
: 'Введите рабочий e-mail. После входа мы привяжем этот Telegram к вашему кабинету.';
|
||||
feedbackTone.value = 'success';
|
||||
} catch (error) {
|
||||
telegramMiniAppMode.value = 'idle';
|
||||
const message = error instanceof Error ? error.message : 'Не получилось проверить Telegram Mini App.';
|
||||
feedback.value = normalizeApolloErrorMessage(message);
|
||||
feedbackTone.value = 'error';
|
||||
}
|
||||
}
|
||||
|
||||
async function startMessengerLogin(channel: 'TELEGRAM' | 'MAX') {
|
||||
if (!isEmailReady.value) {
|
||||
feedback.value = 'Введите корректный email.';
|
||||
@@ -234,7 +312,10 @@ onMounted(async () => {
|
||||
const loginToken = typeof route.query.login_token === 'string' ? route.query.login_token : '';
|
||||
if (loginToken) {
|
||||
await consumeLoginToken(loginToken);
|
||||
return;
|
||||
}
|
||||
|
||||
await tryTelegramMiniAppLogin();
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
@@ -248,6 +329,18 @@ onBeforeUnmount(() => {
|
||||
<div class="card-body p-5 md:p-8">
|
||||
<div class="mb-4 text-center">
|
||||
<h1 class="text-3xl font-extrabold">Вход в личный кабинет</h1>
|
||||
<p
|
||||
v-if="telegramMiniAppMode === 'checking'"
|
||||
class="mt-2 text-sm text-base-content/70"
|
||||
>
|
||||
Проверяем аккаунт Telegram…
|
||||
</p>
|
||||
<p
|
||||
v-else-if="isTelegramMiniApp"
|
||||
class="mt-2 text-sm text-base-content/70"
|
||||
>
|
||||
{{ telegramMiniAppDisplayName ? `Вы вошли из Telegram как ${telegramMiniAppDisplayName}.` : 'Вы открыли кабинет внутри Telegram.' }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div v-if="step === 'request'" class="space-y-4">
|
||||
@@ -265,6 +358,7 @@ onBeforeUnmount(() => {
|
||||
|
||||
<div class="grid gap-2 sm:grid-cols-2">
|
||||
<button
|
||||
v-if="!isTelegramMiniApp"
|
||||
class="btn btn-secondary"
|
||||
:class="{ 'btn-disabled pointer-events-none': !telegramBotUrl || !isEmailReady }"
|
||||
:disabled="pendingChannel === 'TELEGRAM' || !telegramBotUrl || !isEmailReady"
|
||||
|
||||
Reference in New Issue
Block a user