fix: add retry logic for Telegram Mini App auth failures

Auto-retry once on 401 with 1.5s delay, plus a manual retry button
with a hint to reopen the app if auth keeps failing.
This commit is contained in:
c0mrade
2026-02-06 21:53:56 +03:00
parent 692e45ad18
commit a1c0ceba19
5 changed files with 76 additions and 9 deletions

View File

@@ -161,6 +161,8 @@
"or": "or",
"registerHint": "To register with email, first log in via Telegram, then link your email in settings.",
"telegramRequired": "Telegram authorization required",
"telegramRetryFailed": "Authorization failed. Close the app and try again.",
"telegramReopenHint": "If the problem persists, close and reopen the app",
"telegramNotConfigured": "Telegram bot is not configured",
"authenticating": "Authenticating...",
"orOpenInApp": "Or open the bot in the app",

View File

@@ -153,6 +153,8 @@
"or": "یا",
"registerHint": "برای ثبت نام با ایمیل، ابتدا با تلگرام وارد شوید، سپس ایمیل خود را در تنظیمات متصل کنید.",
"telegramRequired": "نیاز به تایید تلگرام",
"telegramRetryFailed": "تایید هویت ناموفق بود. برنامه را ببندید و دوباره باز کنید.",
"telegramReopenHint": "اگر مشکل ادامه دارد، برنامه را ببندید و دوباره باز کنید",
"telegramNotConfigured": "ربات تلگرام پیکربندی نشده",
"authenticating": "در حال تایید هویت...",
"orOpenInApp": "یا ربات را در برنامه باز کنید",

View File

@@ -164,6 +164,8 @@
"or": "или",
"registerHint": "Для регистрации по email сначала авторизуйтесь через Telegram, затем привяжите email в настройках.",
"telegramRequired": "Требуется авторизация через Telegram",
"telegramRetryFailed": "Авторизация не удалась. Закройте приложение и откройте заново.",
"telegramReopenHint": "Если проблема повторяется — закройте и откройте приложение заново",
"telegramNotConfigured": "Telegram бот не настроен",
"authenticating": "Авторизация...",
"orOpenInApp": "Или откройте бота в приложении",

View File

@@ -153,6 +153,8 @@
"or": "或",
"registerHint": "要通过邮箱注册请先通过Telegram登录然后在设置中绑定邮箱。",
"telegramRequired": "需要Telegram授权",
"telegramRetryFailed": "授权失败。请关闭应用后重新打开。",
"telegramReopenHint": "如果问题持续存在,请关闭并重新打开应用",
"telegramNotConfigured": "Telegram机器人未配置",
"authenticating": "正在验证...",
"orOpenInApp": "或在应用中打开机器人",

View File

@@ -110,31 +110,62 @@ export default function Login() {
}
}, [isAuthenticated, navigate, getReturnUrl]);
// Try Telegram WebApp authentication on mount
// Try Telegram WebApp authentication on mount (with auto-retry on 401)
useEffect(() => {
const tryTelegramAuth = async () => {
const initData = getTelegramInitData();
if (isInTelegramWebApp() && initData) {
if (!isInTelegramWebApp() || !initData) return;
setIsTelegramWebApp(true);
// Note: ready() and expand() are already called by SDK init in main.tsx
setIsLoading(true);
const MAX_RETRIES = 1;
for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
try {
await loginWithTelegram(initData);
navigate(getReturnUrl(), { replace: true });
return;
} catch (err) {
const status = (err as { response?: { status?: number } })?.response?.status;
console.warn(`Telegram auth attempt ${attempt + 1} failed with status:`, status);
if (status === 401 && attempt < MAX_RETRIES) {
await new Promise((r) => setTimeout(r, 1500));
continue;
}
setError(t('auth.telegramRequired'));
}
}
setIsLoading(false);
};
tryTelegramAuth();
}, [loginWithTelegram, navigate, t, getReturnUrl]);
// Manual retry for Telegram Mini App auth
const handleRetryTelegramAuth = async () => {
const initData = getTelegramInitData();
if (!initData) {
setError(t('auth.telegramRequired'));
return;
}
setError('');
setIsLoading(true);
try {
await loginWithTelegram(initData);
navigate(getReturnUrl(), { replace: true });
} catch (err) {
// Log only status code to avoid leaking sensitive data
const status = (err as { response?: { status?: number } })?.response?.status;
console.warn('Telegram auth failed with status:', status);
setError(t('auth.telegramRequired'));
console.warn('Telegram auth retry failed with status:', status);
setError(t('auth.telegramRetryFailed', 'Authorization failed. Close the app and try again.'));
} finally {
setIsLoading(false);
}
}
};
tryTelegramAuth();
}, [loginWithTelegram, navigate, t, getReturnUrl]);
const handleEmailSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError('');
@@ -341,6 +372,34 @@ export default function Login() {
<div className="mx-auto mb-3 h-8 w-8 animate-spin rounded-full border-2 border-accent-500 border-t-transparent" />
<p className="text-sm text-dark-400">{t('auth.authenticating')}</p>
</div>
) : isTelegramWebApp && error ? (
<div className="space-y-4 text-center">
<button
onClick={handleRetryTelegramAuth}
className="btn-primary mx-auto flex items-center gap-2 px-6 py-3"
>
<svg
className="h-5 w-5"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
strokeWidth={2}
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M16.023 9.348h4.992v-.001M2.985 19.644v-4.992m0 0h4.992m-4.993 0l3.181 3.183a8.25 8.25 0 0013.803-3.7M4.031 9.865a8.25 8.25 0 0113.803-3.7l3.181 3.182m0-4.991v4.99"
/>
</svg>
{t('auth.tryAgain')}
</button>
<p className="text-xs text-dark-500">
{t(
'auth.telegramReopenHint',
'If the problem persists, close and reopen the app',
)}
</p>
</div>
) : (
<TelegramLoginButton botUsername={botUsername} />
)}