mirror of
https://github.com/chillpadclub/bedolaga-cabinet.git
synced 2026-07-28 09:33:46 +00:00
- Replace unsafe `as` cast with runtime type guard - Pass client_id as Number() per Telegram OIDC spec - Update TypeScript type to string | number
179 lines
7.4 KiB
TypeScript
179 lines
7.4 KiB
TypeScript
import { useEffect, useRef, useState } from 'react';
|
|
import { useTranslation } from 'react-i18next';
|
|
import { useQuery } from '@tanstack/react-query';
|
|
import { brandingApi, type TelegramWidgetConfig } from '../api/branding';
|
|
import { useAuthStore } from '../store/auth';
|
|
import { useNavigate } from 'react-router';
|
|
|
|
interface TelegramLoginButtonProps {
|
|
referralCode?: string;
|
|
}
|
|
|
|
export default function TelegramLoginButton({ referralCode }: TelegramLoginButtonProps) {
|
|
const { t } = useTranslation();
|
|
const navigate = useNavigate();
|
|
const containerRef = useRef<HTMLDivElement>(null);
|
|
const [oidcLoading, setOidcLoading] = useState(false);
|
|
const [oidcError, setOidcError] = useState('');
|
|
const loginWithTelegramOIDC = useAuthStore((s) => s.loginWithTelegramOIDC);
|
|
|
|
const { data: widgetConfig } = useQuery<TelegramWidgetConfig>({
|
|
queryKey: ['telegram-widget-config'],
|
|
queryFn: brandingApi.getTelegramWidgetConfig,
|
|
staleTime: 60000,
|
|
});
|
|
|
|
const botUsername =
|
|
widgetConfig?.bot_username || import.meta.env.VITE_TELEGRAM_BOT_USERNAME || '';
|
|
const isOIDC = Boolean(widgetConfig?.oidc_enabled && widgetConfig?.oidc_client_id);
|
|
|
|
// OIDC callback handler (ref pattern to avoid stale closures and unnecessary re-inits)
|
|
const handleOIDCCallbackRef =
|
|
useRef<(data: { id_token?: string; error?: string }) => void>(undefined);
|
|
|
|
handleOIDCCallbackRef.current = async (data: { id_token?: string; error?: string }) => {
|
|
if (data.error || !data.id_token) {
|
|
setOidcError(data.error || t('auth.loginFailed'));
|
|
setOidcLoading(false);
|
|
return;
|
|
}
|
|
try {
|
|
setOidcLoading(true);
|
|
setOidcError('');
|
|
await loginWithTelegramOIDC(data.id_token);
|
|
navigate('/');
|
|
} catch (err: unknown) {
|
|
let message = t('common.error');
|
|
if (err && typeof err === 'object' && 'response' in err) {
|
|
const resp = (err as { response?: { data?: { detail?: string } } }).response;
|
|
if (resp?.data?.detail) message = resp.data.detail;
|
|
}
|
|
setOidcError(message);
|
|
} finally {
|
|
setOidcLoading(false);
|
|
}
|
|
};
|
|
|
|
// Load OIDC script and init
|
|
useEffect(() => {
|
|
if (!isOIDC || !widgetConfig?.oidc_client_id) return;
|
|
|
|
const scriptId = 'telegram-login-oidc-script';
|
|
let script = document.getElementById(scriptId) as HTMLScriptElement | null;
|
|
|
|
const initTelegramLogin = () => {
|
|
if (window.Telegram?.Login) {
|
|
window.Telegram.Login.init(
|
|
{
|
|
client_id: Number(widgetConfig.oidc_client_id) || widgetConfig.oidc_client_id,
|
|
request_access: widgetConfig.request_access ? ['write'] : undefined,
|
|
lang: document.documentElement.lang || 'en',
|
|
},
|
|
(data) => handleOIDCCallbackRef.current?.(data),
|
|
);
|
|
}
|
|
};
|
|
|
|
if (!script) {
|
|
script = document.createElement('script');
|
|
script.id = scriptId;
|
|
script.src = 'https://oauth.telegram.org/js/telegram-login.js?3';
|
|
script.async = true;
|
|
script.onload = initTelegramLogin;
|
|
document.head.appendChild(script);
|
|
} else {
|
|
// Script already loaded, just re-init
|
|
initTelegramLogin();
|
|
}
|
|
}, [isOIDC, widgetConfig?.oidc_client_id, widgetConfig?.request_access]);
|
|
|
|
// Legacy widget effect (only when NOT OIDC)
|
|
useEffect(() => {
|
|
if (isOIDC || !containerRef.current || !botUsername || !widgetConfig) return;
|
|
|
|
const container = containerRef.current;
|
|
while (container.firstChild) {
|
|
container.removeChild(container.firstChild);
|
|
}
|
|
|
|
const redirectUrl = `${window.location.origin}/auth/telegram/callback`;
|
|
|
|
const script = document.createElement('script');
|
|
script.src = 'https://telegram.org/js/telegram-widget.js?23';
|
|
script.setAttribute('data-telegram-login', botUsername);
|
|
script.setAttribute('data-size', widgetConfig.size);
|
|
script.setAttribute('data-radius', String(widgetConfig.radius));
|
|
script.setAttribute('data-userpic', String(widgetConfig.userpic));
|
|
script.setAttribute('data-auth-url', redirectUrl);
|
|
if (widgetConfig.request_access) {
|
|
script.setAttribute('data-request-access', 'write');
|
|
}
|
|
script.async = true;
|
|
|
|
container.appendChild(script);
|
|
|
|
return () => {
|
|
while (container.firstChild) {
|
|
container.removeChild(container.firstChild);
|
|
}
|
|
};
|
|
}, [isOIDC, botUsername, widgetConfig]);
|
|
|
|
if (!botUsername || botUsername === 'your_bot') {
|
|
return (
|
|
<div className="py-4 text-center text-sm text-gray-500">
|
|
{t('auth.telegramNotConfigured')}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
return (
|
|
<div className="flex flex-col items-center space-y-4">
|
|
{/* OIDC mode: custom button that opens popup */}
|
|
{isOIDC ? (
|
|
<div className="flex flex-col items-center space-y-2">
|
|
<button
|
|
type="button"
|
|
onClick={() => {
|
|
setOidcError('');
|
|
if (window.Telegram?.Login) {
|
|
window.Telegram.Login.open();
|
|
}
|
|
}}
|
|
disabled={oidcLoading}
|
|
className="inline-flex items-center gap-2 rounded-lg bg-[#54a9eb] px-6 py-3 text-sm font-medium text-white shadow-sm transition-colors hover:bg-[#4a96d2] disabled:opacity-50"
|
|
>
|
|
<svg className="h-5 w-5" viewBox="0 0 24 24" fill="currentColor">
|
|
<path d="M11.944 0A12 12 0 0 0 0 12a12 12 0 0 0 12 12 12 12 0 0 0 12-12A12 12 0 0 0 12 0a12 12 0 0 0-.056 0zm4.962 7.224c.1-.002.321.023.465.14a.506.506 0 0 1 .171.325c.016.093.036.306.02.472-.18 1.898-.962 6.502-1.36 8.627-.168.9-.499 1.201-.82 1.23-.696.065-1.225-.46-1.9-.902-1.056-.693-1.653-1.124-2.678-1.8-1.185-.78-.417-1.21.258-1.91.177-.184 3.247-2.977 3.307-3.23.007-.032.014-.15-.056-.212s-.174-.041-.249-.024c-.106.024-1.793 1.14-5.061 3.345-.48.33-.913.49-1.302.48-.428-.008-1.252-.241-1.865-.44-.752-.245-1.349-.374-1.297-.789.027-.216.325-.437.893-.663 3.498-1.524 5.83-2.529 6.998-3.014 3.332-1.386 4.025-1.627 4.476-1.635z" />
|
|
</svg>
|
|
{oidcLoading ? t('common.loading') : t('auth.loginWithTelegram')}
|
|
</button>
|
|
{oidcError && <p className="text-xs text-red-500">{oidcError}</p>}
|
|
</div>
|
|
) : (
|
|
/* Legacy widget mode: iframe-based widget */
|
|
<div ref={containerRef} className="flex justify-center" />
|
|
)}
|
|
|
|
<div className="text-center">
|
|
<p className="mb-2 text-xs text-gray-500">{t('auth.orOpenInApp')}</p>
|
|
<a
|
|
href={
|
|
referralCode
|
|
? `https://t.me/${botUsername}?start=${encodeURIComponent(referralCode)}`
|
|
: `https://t.me/${botUsername}`
|
|
}
|
|
target="_blank"
|
|
rel="noopener noreferrer"
|
|
className="text-telegram-blue inline-flex items-center text-sm hover:underline"
|
|
>
|
|
<svg className="mr-1 h-4 w-4" viewBox="0 0 24 24" fill="currentColor">
|
|
<path d="M11.944 0A12 12 0 0 0 0 12a12 12 0 0 0 12 12 12 12 0 0 0 12-12A12 12 0 0 0 12 0a12 12 0 0 0-.056 0zm4.962 7.224c.1-.002.321.023.465.14a.506.506 0 0 1 .171.325c.016.093.036.306.02.472-.18 1.898-.962 6.502-1.36 8.627-.168.9-.499 1.201-.82 1.23-.696.065-1.225-.46-1.9-.902-1.056-.693-1.653-1.124-2.678-1.8-1.185-.78-.417-1.21.258-1.91.177-.184 3.247-2.977 3.307-3.23.007-.032.014-.15-.056-.212s-.174-.041-.249-.024c-.106.024-1.793 1.14-5.061 3.345-.48.33-.913.49-1.302.48-.428-.008-1.252-.241-1.865-.44-.752-.245-1.349-.374-1.297-.789.027-.216.325-.437.893-.663 3.498-1.524 5.83-2.529 6.998-3.014 3.332-1.386 4.025-1.627 4.476-1.635z" />
|
|
</svg>
|
|
@{botUsername}
|
|
</a>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|