Update files
This commit is contained in:
parent
7fadcf4f53
commit
9beca1efcd
|
|
@ -360,6 +360,9 @@ async def login(request: LoginRequest, response: Response):
|
|||
|
||||
@router.post("/telegram-widget")
|
||||
async def telegram_widget_auth(request: TelegramWidgetAuth, response: Response):
|
||||
print(f"[ModerationAuth] 📥 Запрос авторизации через Telegram виджет")
|
||||
print(f"[ModerationAuth] Полученные данные: id={request.id}, username={request.username}, first_name={request.first_name}")
|
||||
print(f"[ModerationAuth] hash={request.hash[:20] if request.hash else 'None'}..., auth_date={request.auth_date}")
|
||||
"""Authenticate via Telegram Login Widget"""
|
||||
print(f"[ModerationAuth] 🔍 Запрос авторизации через Telegram виджет: id={request.id}, username={request.username}")
|
||||
|
||||
|
|
|
|||
|
|
@ -239,56 +239,79 @@ export default function App() {
|
|||
if (!telegramApp?.initData && showLoginForm && telegramWidgetRef.current) {
|
||||
// Глобальная функция для обработки авторизации через виджет
|
||||
window.onTelegramAuth = async (userData) => {
|
||||
console.log('Telegram Login Widget данные:', userData);
|
||||
console.log('[Telegram Widget] 🔵 onTelegramAuth вызван!');
|
||||
console.log('[Telegram Widget] Данные от виджета:', userData);
|
||||
console.log('[Telegram Widget] Тип данных:', typeof userData);
|
||||
console.log('[Telegram Widget] Ключи:', userData ? Object.keys(userData) : 'null');
|
||||
|
||||
if (!userData) {
|
||||
console.error('[Telegram Widget] ❌ userData пустой!');
|
||||
setError('Данные от Telegram виджета не получены');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setAuthLoading(true);
|
||||
setError(null);
|
||||
|
||||
// Отправить данные виджета на сервер для создания сессии
|
||||
const API_URL = getApiUrl();
|
||||
// В production используем относительный путь (HTTPS через nginx)
|
||||
const fullApiUrl = API_URL.startsWith('http') ? API_URL : `${window.location.origin}${API_URL}`;
|
||||
const response = await fetch(`${fullApiUrl}/moderation-auth/telegram-widget`, {
|
||||
const endpoint = `${fullApiUrl}/moderation-auth/telegram-widget`;
|
||||
|
||||
console.log('[Telegram Widget] Отправка запроса на:', endpoint);
|
||||
console.log('[Telegram Widget] Данные для отправки:', JSON.stringify(userData, null, 2));
|
||||
|
||||
const response = await fetch(endpoint, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
credentials: 'include',
|
||||
body: JSON.stringify(userData)
|
||||
});
|
||||
|
||||
console.log('[Telegram Widget] Ответ получен:', response.status, response.statusText);
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => ({}));
|
||||
throw new Error(errorData.error || 'Ошибка авторизации');
|
||||
console.error('[Telegram Widget] ❌ Ошибка ответа:', errorData);
|
||||
throw new Error(errorData.detail || errorData.error || `Ошибка ${response.status}: ${response.statusText}`);
|
||||
}
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
console.log('[Telegram Widget] Результат авторизации:', result);
|
||||
console.log('[Telegram Widget] ✅ Результат авторизации:', result);
|
||||
|
||||
if (result.accessToken) {
|
||||
localStorage.setItem('moderation_jwt_token', result.accessToken);
|
||||
console.log('[Telegram Widget] Токен сохранен');
|
||||
console.log('[Telegram Widget] ✅ Токен сохранен');
|
||||
}
|
||||
|
||||
if (result?.user) {
|
||||
setUser(result.user);
|
||||
setError(null);
|
||||
console.log('[Telegram Widget] Пользователь установлен:', result.user.username);
|
||||
console.log('[Telegram Widget] ✅ Пользователь установлен:', result.user.username);
|
||||
|
||||
// Перенаправить на главную страницу после успешной авторизации
|
||||
setTimeout(() => {
|
||||
console.log('[Telegram Widget] Перенаправление на главную страницу...');
|
||||
window.location.href = '/';
|
||||
}, 500);
|
||||
} else {
|
||||
console.error('[Telegram Widget] ❌ Пользователь не получен от сервера');
|
||||
throw new Error('Пользователь не получен от сервера');
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Ошибка авторизации через виджет:', err);
|
||||
console.error('[Telegram Widget] ❌ Ошибка авторизации через виджет:', err);
|
||||
console.error('[Telegram Widget] Stack:', err.stack);
|
||||
setError(err.message || 'Ошибка авторизации через Telegram');
|
||||
} finally {
|
||||
setAuthLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
console.log('[Telegram Widget] ✅ window.onTelegramAuth установлен');
|
||||
|
||||
const initWidget = () => {
|
||||
// Проверить не загружен ли уже виджет
|
||||
if (document.querySelector('script[src*="telegram-widget"]')) {
|
||||
|
|
@ -324,11 +347,23 @@ export default function App() {
|
|||
console.log('[Telegram Widget] Current origin:', window.location.origin);
|
||||
|
||||
script.onload = () => {
|
||||
console.log('[Telegram Widget] Скрипт загружен');
|
||||
console.log('[Telegram Widget] ✅ Скрипт виджета загружен');
|
||||
console.log('[Telegram Widget] Проверка window.onTelegramAuth:', typeof window.onTelegramAuth);
|
||||
|
||||
// Проверить, что виджет создался
|
||||
setTimeout(() => {
|
||||
const widgetElement = widgetContainer.querySelector('iframe, div');
|
||||
if (widgetElement) {
|
||||
console.log('[Telegram Widget] ✅ Виджет отрендерен в DOM');
|
||||
} else {
|
||||
console.warn('[Telegram Widget] ⚠️ Виджет не найден в DOM после загрузки');
|
||||
}
|
||||
}, 1000);
|
||||
};
|
||||
|
||||
script.onerror = () => {
|
||||
console.error('[Telegram Widget] Ошибка загрузки скрипта');
|
||||
script.onerror = (error) => {
|
||||
console.error('[Telegram Widget] ❌ Ошибка загрузки скрипта:', error);
|
||||
setError('Не удалось загрузить Telegram виджет');
|
||||
};
|
||||
|
||||
widgetContainer.appendChild(script);
|
||||
|
|
|
|||
Loading…
Reference in New Issue