diff --git a/src/App.tsx b/src/App.tsx index eb2d837..f51c9d5 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -41,6 +41,7 @@ const TopUpMethodSelect = lazy(() => import('./pages/TopUpMethodSelect')); const TopUpAmount = lazy(() => import('./pages/TopUpAmount')); const ConnectedAccounts = lazy(() => import('./pages/ConnectedAccounts')); const LinkOAuthCallback = lazy(() => import('./pages/LinkOAuthCallback')); +const LinkTelegramCallback = lazy(() => import('./pages/LinkTelegramCallback')); const MergeAccounts = lazy(() => import('./pages/MergeAccounts')); // Admin pages - lazy load (only for admins) @@ -326,6 +327,16 @@ function App() { } /> + + + + + + } + /> => { + const response = await apiClient.post( + '/cabinet/auth/account/link/telegram', + data, + ); + return response.data; + }, + unlinkProvider: async (provider: string): Promise<{ success: boolean }> => { const response = await apiClient.post<{ success: boolean }>( `/cabinet/auth/account/unlink/${encodeURIComponent(provider)}`, diff --git a/src/locales/en.json b/src/locales/en.json index 7ce6a4d..9bc63d9 100644 --- a/src/locales/en.json +++ b/src/locales/en.json @@ -3615,6 +3615,8 @@ "unlinkError": "Failed to disconnect account", "goToAccounts": "Connected Accounts", "linking": "Linking account...", + "linkTelegramWidget": "Sign in with Telegram to connect", + "linkingTelegram": "Connecting Telegram...", "providers": { "telegram": "Telegram", "email": "Email", diff --git a/src/locales/fa.json b/src/locales/fa.json index b1de938..e4f9993 100644 --- a/src/locales/fa.json +++ b/src/locales/fa.json @@ -3051,6 +3051,8 @@ "unlinkError": "قطع اتصال ناموفق بود", "goToAccounts": "حساب‌های متصل", "linking": "در حال اتصال حساب...", + "linkTelegramWidget": "برای اتصال از طریق تلگرام وارد شوید", + "linkingTelegram": "در حال اتصال تلگرام...", "providers": { "telegram": "تلگرام", "email": "ایمیل", diff --git a/src/locales/ru.json b/src/locales/ru.json index 4a1e108..80c11de 100644 --- a/src/locales/ru.json +++ b/src/locales/ru.json @@ -4175,6 +4175,8 @@ "unlinkError": "Не удалось отвязать аккаунт", "goToAccounts": "Привязанные аккаунты", "linking": "Привязка аккаунта...", + "linkTelegramWidget": "Войдите через Telegram для привязки", + "linkingTelegram": "Привязка Telegram...", "providers": { "telegram": "Telegram", "email": "Email", diff --git a/src/locales/zh.json b/src/locales/zh.json index 7caeace..b78e260 100644 --- a/src/locales/zh.json +++ b/src/locales/zh.json @@ -3050,6 +3050,8 @@ "unlinkError": "取消关联失败", "goToAccounts": "关联账户", "linking": "正在关联账户...", + "linkTelegramWidget": "通过 Telegram 登录以关联", + "linkingTelegram": "正在关联 Telegram...", "providers": { "telegram": "Telegram", "email": "邮箱", diff --git a/src/pages/ConnectedAccounts.tsx b/src/pages/ConnectedAccounts.tsx index ce1ae0e..7b7386f 100644 --- a/src/pages/ConnectedAccounts.tsx +++ b/src/pages/ConnectedAccounts.tsx @@ -1,5 +1,6 @@ import { useState, useEffect, useRef } from 'react'; import { useTranslation } from 'react-i18next'; +import { useNavigate } from 'react-router'; import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'; import { motion } from 'framer-motion'; import { authApi } from '../api/auth'; @@ -9,12 +10,63 @@ import { Button } from '@/components/primitives/Button'; import { staggerContainer, staggerItem } from '@/components/motion/transitions'; import ProviderIcon from '../components/ProviderIcon'; import { LINK_OAUTH_STATE_KEY, LINK_OAUTH_PROVIDER_KEY } from './LinkOAuthCallback'; +import { isInTelegramWebApp, getTelegramInitData } from '../hooks/useTelegramSDK'; import type { LinkedProvider } from '../types'; const OAUTH_PROVIDERS = ['google', 'yandex', 'discord', 'vk']; const isOAuthProvider = (provider: string): boolean => OAUTH_PROVIDERS.includes(provider); +const isLinkableProvider = (provider: string): boolean => + isOAuthProvider(provider) || provider === 'telegram'; + +// SessionStorage key for Telegram link CSRF state +export const LINK_TELEGRAM_STATE_KEY = 'link_telegram_state'; + +/** Compact Telegram Login Widget for account linking (browser only). */ +function TelegramLinkWidget() { + const containerRef = useRef(null); + const botUsername = import.meta.env.VITE_TELEGRAM_BOT_USERNAME || ''; + + useEffect(() => { + if (!containerRef.current || !botUsername) return; + + const container = containerRef.current; + while (container.firstChild) { + container.removeChild(container.firstChild); + } + + // Generate CSRF state token and store in sessionStorage + const csrfState = crypto.randomUUID(); + sessionStorage.setItem(LINK_TELEGRAM_STATE_KEY, csrfState); + + const redirectUrl = `${window.location.origin}/auth/link/telegram/callback?csrf_state=${encodeURIComponent(csrfState)}`; + + const script = document.createElement('script'); + script.src = 'https://telegram.org/js/telegram-widget.js?22'; + script.setAttribute('data-telegram-login', botUsername); + script.setAttribute('data-size', 'small'); + script.setAttribute('data-radius', '8'); + script.setAttribute('data-auth-url', redirectUrl); + script.setAttribute('data-request-access', 'write'); + script.async = true; + + container.appendChild(script); + + return () => { + while (container.firstChild) { + container.removeChild(container.firstChild); + } + }; + }, [botUsername]); + + if (!botUsername) { + return null; + } + + return
; +} + function LoadingSkeleton() { return (
@@ -40,11 +92,14 @@ export default function ConnectedAccounts() { const { t } = useTranslation(); const { showToast } = useToast(); const queryClient = useQueryClient(); + const navigate = useNavigate(); const [confirmingUnlink, setConfirmingUnlink] = useState(null); const [linkingProvider, setLinkingProvider] = useState(null); const blurTimeoutRef = useRef>(undefined); + const inTelegram = isInTelegramWebApp(); + useEffect(() => { return () => { if (blurTimeoutRef.current) clearTimeout(blurTimeoutRef.current); @@ -83,7 +138,7 @@ export default function ConnectedAccounts() { return linkedCount > 1; }; - const handleLink = async (provider: string) => { + const handleLinkOAuth = async (provider: string) => { if (linkingProvider) return; setLinkingProvider(provider); try { @@ -100,6 +155,35 @@ export default function ConnectedAccounts() { } }; + const handleLinkTelegram = async () => { + if (linkingProvider) return; + const initData = getTelegramInitData(); + if (!initData) return; + + setLinkingProvider('telegram'); + try { + const response = await authApi.linkTelegram({ init_data: initData }); + if (response.merge_required && response.merge_token) { + navigate(`/merge/${response.merge_token}`, { replace: true }); + } else { + queryClient.invalidateQueries({ queryKey: ['linked-providers'] }); + showToast({ type: 'success', message: t('profile.accounts.linkSuccess') }); + } + } catch { + showToast({ type: 'error', message: t('profile.accounts.linkError') }); + } finally { + setLinkingProvider(null); + } + }; + + const handleLink = async (provider: string) => { + if (provider === 'telegram') { + await handleLinkTelegram(); + } else { + await handleLinkOAuth(provider); + } + }; + const handleUnlink = (provider: string) => { if (confirmingUnlink === provider) { setConfirmingUnlink(null); @@ -109,6 +193,43 @@ export default function ConnectedAccounts() { } }; + const renderLinkButton = (provider: LinkedProvider) => { + if (provider.provider === 'telegram') { + if (inTelegram && getTelegramInitData()) { + // Mini App: one-click button + return ( + + ); + } + // Browser: Telegram Login Widget + return ; + } + + if (isOAuthProvider(provider.provider)) { + return ( + + ); + } + + return null; + }; + return ( handleUnlink(provider.provider)} onBlur={() => { - // Delay so click on the same button fires before blur resets state blurTimeoutRef.current = setTimeout(() => { setConfirmingUnlink((cur) => (cur === provider.provider ? null : cur)); }, 150); @@ -183,17 +303,7 @@ export default function ConnectedAccounts() { )} ) : ( - isOAuthProvider(provider.provider) && ( - - ) + isLinkableProvider(provider.provider) && renderLinkButton(provider) )}
diff --git a/src/pages/LinkTelegramCallback.tsx b/src/pages/LinkTelegramCallback.tsx new file mode 100644 index 0000000..9fec27b --- /dev/null +++ b/src/pages/LinkTelegramCallback.tsx @@ -0,0 +1,93 @@ +import { useEffect, useRef } from 'react'; +import { useNavigate, useSearchParams } from 'react-router'; +import { useTranslation } from 'react-i18next'; +import { authApi } from '../api/auth'; +import { useToast } from '../components/Toast'; +import { LINK_TELEGRAM_STATE_KEY } from './ConnectedAccounts'; + +export default function LinkTelegramCallback() { + const { t } = useTranslation(); + const navigate = useNavigate(); + const [searchParams] = useSearchParams(); + const { showToast } = useToast(); + const hasRun = useRef(false); + + useEffect(() => { + if (hasRun.current) return; + hasRun.current = true; + + // Clear sensitive data from URL immediately + window.history.replaceState({}, '', '/auth/link/telegram/callback'); + + const linkAccount = async () => { + // 1. Validate CSRF state + const csrfState = searchParams.get('csrf_state'); + const savedState = sessionStorage.getItem(LINK_TELEGRAM_STATE_KEY); + sessionStorage.removeItem(LINK_TELEGRAM_STATE_KEY); + + if (!csrfState || !savedState || csrfState !== savedState) { + showToast({ type: 'error', message: t('profile.accounts.linkError') }); + navigate('/profile/accounts', { replace: true }); + return; + } + + // 2. Validate required Telegram fields + const id = searchParams.get('id'); + const firstName = searchParams.get('first_name'); + const authDate = searchParams.get('auth_date'); + const hash = searchParams.get('hash'); + + if (!id || !firstName || !authDate || !hash) { + showToast({ type: 'error', message: t('profile.accounts.linkError') }); + navigate('/profile/accounts', { replace: true }); + return; + } + + const parsedId = parseInt(id, 10); + const parsedAuthDate = parseInt(authDate, 10); + + if (Number.isNaN(parsedId) || Number.isNaN(parsedAuthDate)) { + showToast({ type: 'error', message: t('profile.accounts.linkError') }); + navigate('/profile/accounts', { replace: true }); + return; + } + + try { + const response = await authApi.linkTelegram({ + id: parsedId, + first_name: firstName, + last_name: searchParams.get('last_name') || undefined, + username: searchParams.get('username') || undefined, + photo_url: searchParams.get('photo_url') || undefined, + auth_date: parsedAuthDate, + hash, + }); + + if (response.merge_required && response.merge_token) { + navigate(`/merge/${response.merge_token}`, { replace: true }); + } else { + showToast({ type: 'success', message: t('profile.accounts.linkSuccess') }); + navigate('/profile/accounts', { replace: true }); + } + } catch { + showToast({ type: 'error', message: t('profile.accounts.linkError') }); + navigate('/profile/accounts', { replace: true }); + } + }; + + linkAccount(); + }, [searchParams, navigate, showToast, t]); + + return ( +
+
+
+
+

+ {t('profile.accounts.linkingTelegram')} +

+

{t('common.loading')}

+
+
+ ); +}