Add Telegram Mini App login flow
This commit is contained in:
61
app/composables/useTelegramMiniApp.ts
Normal file
61
app/composables/useTelegramMiniApp.ts
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
type TelegramMiniAppUser = {
|
||||||
|
id: number | string;
|
||||||
|
first_name?: string;
|
||||||
|
last_name?: string;
|
||||||
|
username?: string;
|
||||||
|
language_code?: string;
|
||||||
|
photo_url?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
type TelegramWebApp = {
|
||||||
|
initData?: string;
|
||||||
|
initDataUnsafe?: {
|
||||||
|
user?: TelegramMiniAppUser;
|
||||||
|
start_param?: string;
|
||||||
|
};
|
||||||
|
ready?: () => void;
|
||||||
|
expand?: () => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
declare global {
|
||||||
|
interface Window {
|
||||||
|
Telegram?: {
|
||||||
|
WebApp?: TelegramWebApp;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildDisplayName(user: TelegramMiniAppUser | null) {
|
||||||
|
if (!user) {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
const firstName = String(user.first_name || '').trim();
|
||||||
|
const lastName = String(user.last_name || '').trim();
|
||||||
|
return `${firstName} ${lastName}`.trim() || firstName || String(user.username || '').trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useTelegramMiniApp() {
|
||||||
|
const webApp = computed<TelegramWebApp | null>(() => {
|
||||||
|
if (!import.meta.client) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return window.Telegram?.WebApp ?? null;
|
||||||
|
});
|
||||||
|
|
||||||
|
const initData = computed(() => String(webApp.value?.initData || '').trim());
|
||||||
|
const user = computed<TelegramMiniAppUser | null>(() => webApp.value?.initDataUnsafe?.user ?? null);
|
||||||
|
const startParam = computed(() => String(webApp.value?.initDataUnsafe?.start_param || '').trim());
|
||||||
|
const isAvailable = computed(() => Boolean(initData.value));
|
||||||
|
const displayName = computed(() => buildDisplayName(user.value));
|
||||||
|
|
||||||
|
return {
|
||||||
|
webApp,
|
||||||
|
initData,
|
||||||
|
user,
|
||||||
|
startParam,
|
||||||
|
isAvailable,
|
||||||
|
displayName,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -4,11 +4,22 @@ export default defineNuxtRouteMiddleware((to) => {
|
|||||||
const authToken = useCookie<string | null>(authCookieName);
|
const authToken = useCookie<string | null>(authCookieName);
|
||||||
|
|
||||||
const isLoginPage = to.path === '/login';
|
const isLoginPage = to.path === '/login';
|
||||||
|
const loginToken = typeof to.query.login_token === 'string' ? to.query.login_token.trim() : '';
|
||||||
|
const nextPath = to.fullPath.startsWith('/') ? to.fullPath : '/';
|
||||||
|
|
||||||
if (!authToken.value && !isLoginPage) {
|
if (!authToken.value && !isLoginPage) {
|
||||||
return navigateTo('/login');
|
return navigateTo({
|
||||||
|
path: '/login',
|
||||||
|
query: {
|
||||||
|
next: nextPath,
|
||||||
|
},
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
if (authToken.value && isLoginPage) {
|
if (authToken.value && isLoginPage && !loginToken) {
|
||||||
return navigateTo('/');
|
const requestedNextPath = typeof to.query.next === 'string' && to.query.next.startsWith('/')
|
||||||
|
? to.query.next
|
||||||
|
: '/';
|
||||||
|
return navigateTo(requestedNextPath);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import {
|
|||||||
VerifyLoginCodeDocument,
|
VerifyLoginCodeDocument,
|
||||||
} from '~/composables/graphql/generated';
|
} from '~/composables/graphql/generated';
|
||||||
import { useMessengerStart } from '~/composables/useMessengerStart';
|
import { useMessengerStart } from '~/composables/useMessengerStart';
|
||||||
|
import { useTelegramMiniApp } from '~/composables/useTelegramMiniApp';
|
||||||
|
|
||||||
const config = useRuntimeConfig();
|
const config = useRuntimeConfig();
|
||||||
const route = useRoute();
|
const route = useRoute();
|
||||||
@@ -30,19 +31,31 @@ const requestCodeMutation = useMutation(RequestLoginCodeDocument, { throws: 'nev
|
|||||||
const verifyCodeMutation = useMutation(VerifyLoginCodeDocument, { throws: 'never' });
|
const verifyCodeMutation = useMutation(VerifyLoginCodeDocument, { throws: 'never' });
|
||||||
const consumeLoginTokenMutation = useMutation(ConsumeLoginTokenDocument, { throws: 'never' });
|
const consumeLoginTokenMutation = useMutation(ConsumeLoginTokenDocument, { throws: 'never' });
|
||||||
const { openMessengerBot, pendingChannel } = useMessengerStart();
|
const { openMessengerBot, pendingChannel } = useMessengerStart();
|
||||||
|
const { isAvailable: isTelegramMiniApp, initData: telegramMiniAppInitData, displayName: telegramMiniAppDisplayName } = useTelegramMiniApp();
|
||||||
|
|
||||||
const telegramBotUrl = computed(() => config.public.telegramBotUrl || '');
|
const telegramBotUrl = computed(() => config.public.telegramBotUrl || '');
|
||||||
const maxBotUrl = computed(() => config.public.maxBotUrl || '');
|
const maxBotUrl = computed(() => config.public.maxBotUrl || '');
|
||||||
|
|
||||||
const normalizedEmail = computed(() => email.value.trim().toLowerCase());
|
const normalizedEmail = computed(() => email.value.trim().toLowerCase());
|
||||||
const isEmailReady = computed(() => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(normalizedEmail.value));
|
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) {
|
async function finalizeSession(accessToken: string) {
|
||||||
authCookie.value = accessToken;
|
authCookie.value = accessToken;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function navigateAfterLogin(user: { company?: { id: string } | null }) {
|
async function navigateAfterLogin(user: { company?: { id: string } | null; companyId?: string | null }) {
|
||||||
if (!user.company?.id) {
|
if (nextPath.value) {
|
||||||
|
await navigateTo(nextPath.value);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!user.company?.id && !user.companyId) {
|
||||||
await navigateTo('/profile');
|
await navigateTo('/profile');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -63,6 +76,9 @@ function normalizeApolloErrorMessage(message: string) {
|
|||||||
if (message.includes('User for this destination was not found.')) {
|
if (message.includes('User for this destination was not found.')) {
|
||||||
return 'Пользователь с таким e-mail не найден. Вход доступен только для созданных аккаунтов.';
|
return 'Пользователь с таким e-mail не найден. Вход доступен только для созданных аккаунтов.';
|
||||||
}
|
}
|
||||||
|
if (message.includes('Telegram initData')) {
|
||||||
|
return 'Не получилось проверить Telegram Mini App. Откройте кабинет из Telegram заново.';
|
||||||
|
}
|
||||||
return message;
|
return message;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -143,6 +159,7 @@ async function verifyCode() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
await finalizeSession(payload.accessToken);
|
await finalizeSession(payload.accessToken);
|
||||||
|
await connectTelegramMiniApp();
|
||||||
await navigateAfterLogin(payload.user);
|
await navigateAfterLogin(payload.user);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -166,6 +183,67 @@ async function consumeLoginToken(loginToken: string) {
|
|||||||
await navigateAfterLogin(payload.user);
|
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') {
|
async function startMessengerLogin(channel: 'TELEGRAM' | 'MAX') {
|
||||||
if (!isEmailReady.value) {
|
if (!isEmailReady.value) {
|
||||||
feedback.value = 'Введите корректный email.';
|
feedback.value = 'Введите корректный email.';
|
||||||
@@ -234,7 +312,10 @@ onMounted(async () => {
|
|||||||
const loginToken = typeof route.query.login_token === 'string' ? route.query.login_token : '';
|
const loginToken = typeof route.query.login_token === 'string' ? route.query.login_token : '';
|
||||||
if (loginToken) {
|
if (loginToken) {
|
||||||
await consumeLoginToken(loginToken);
|
await consumeLoginToken(loginToken);
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
await tryTelegramMiniAppLogin();
|
||||||
});
|
});
|
||||||
|
|
||||||
onBeforeUnmount(() => {
|
onBeforeUnmount(() => {
|
||||||
@@ -248,6 +329,18 @@ onBeforeUnmount(() => {
|
|||||||
<div class="card-body p-5 md:p-8">
|
<div class="card-body p-5 md:p-8">
|
||||||
<div class="mb-4 text-center">
|
<div class="mb-4 text-center">
|
||||||
<h1 class="text-3xl font-extrabold">Вход в личный кабинет</h1>
|
<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>
|
||||||
|
|
||||||
<div v-if="step === 'request'" class="space-y-4">
|
<div v-if="step === 'request'" class="space-y-4">
|
||||||
@@ -265,6 +358,7 @@ onBeforeUnmount(() => {
|
|||||||
|
|
||||||
<div class="grid gap-2 sm:grid-cols-2">
|
<div class="grid gap-2 sm:grid-cols-2">
|
||||||
<button
|
<button
|
||||||
|
v-if="!isTelegramMiniApp"
|
||||||
class="btn btn-secondary"
|
class="btn btn-secondary"
|
||||||
:class="{ 'btn-disabled pointer-events-none': !telegramBotUrl || !isEmailReady }"
|
:class="{ 'btn-disabled pointer-events-none': !telegramBotUrl || !isEmailReady }"
|
||||||
:disabled="pendingChannel === 'TELEGRAM' || !telegramBotUrl || !isEmailReady"
|
:disabled="pendingChannel === 'TELEGRAM' || !telegramBotUrl || !isEmailReady"
|
||||||
|
|||||||
9
app/plugins/telegram-mini-app.client.ts
Normal file
9
app/plugins/telegram-mini-app.client.ts
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
export default defineNuxtPlugin(() => {
|
||||||
|
const { webApp, isAvailable } = useTelegramMiniApp();
|
||||||
|
if (!isAvailable.value || !webApp.value) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
webApp.value.ready?.();
|
||||||
|
webApp.value.expand?.();
|
||||||
|
});
|
||||||
@@ -42,6 +42,7 @@ export default defineNuxtConfig({
|
|||||||
head: {
|
head: {
|
||||||
title: 'Fregat Client Cabinet',
|
title: 'Fregat Client Cabinet',
|
||||||
meta: [{ name: 'viewport', content: 'width=device-width, initial-scale=1' }],
|
meta: [{ name: 'viewport', content: 'width=device-width, initial-scale=1' }],
|
||||||
|
script: [{ src: 'https://telegram.org/js/telegram-web-app.js?61' }],
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|||||||
27
server/api/auth/telegram-mini-app/connect.post.ts
Normal file
27
server/api/auth/telegram-mini-app/connect.post.ts
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
export default defineEventHandler(async (event) => {
|
||||||
|
const config = useRuntimeConfig(event);
|
||||||
|
const backendUrl = new URL(config.backendGraphqlUrl);
|
||||||
|
const endpoint = `${backendUrl.origin}/auth/telegram-mini-app/connect`;
|
||||||
|
const body = await readBody(event);
|
||||||
|
|
||||||
|
const cookie = getHeader(event, 'cookie');
|
||||||
|
const authorization = getHeader(event, 'authorization');
|
||||||
|
|
||||||
|
const response = await fetch(endpoint, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'content-type': 'application/json',
|
||||||
|
...(cookie ? { cookie } : {}),
|
||||||
|
...(authorization ? { authorization } : {}),
|
||||||
|
},
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
});
|
||||||
|
|
||||||
|
setResponseStatus(event, response.status);
|
||||||
|
const contentType = response.headers.get('content-type');
|
||||||
|
if (contentType) {
|
||||||
|
setHeader(event, 'content-type', contentType);
|
||||||
|
}
|
||||||
|
|
||||||
|
return await response.json();
|
||||||
|
});
|
||||||
27
server/api/auth/telegram-mini-app/session.post.ts
Normal file
27
server/api/auth/telegram-mini-app/session.post.ts
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
export default defineEventHandler(async (event) => {
|
||||||
|
const config = useRuntimeConfig(event);
|
||||||
|
const backendUrl = new URL(config.backendGraphqlUrl);
|
||||||
|
const endpoint = `${backendUrl.origin}/auth/telegram-mini-app/session`;
|
||||||
|
const body = await readBody(event);
|
||||||
|
|
||||||
|
const cookie = getHeader(event, 'cookie');
|
||||||
|
const authorization = getHeader(event, 'authorization');
|
||||||
|
|
||||||
|
const response = await fetch(endpoint, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'content-type': 'application/json',
|
||||||
|
...(cookie ? { cookie } : {}),
|
||||||
|
...(authorization ? { authorization } : {}),
|
||||||
|
},
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
});
|
||||||
|
|
||||||
|
setResponseStatus(event, response.status);
|
||||||
|
const contentType = response.headers.get('content-type');
|
||||||
|
if (contentType) {
|
||||||
|
setHeader(event, 'content-type', contentType);
|
||||||
|
}
|
||||||
|
|
||||||
|
return await response.json();
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user