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")
|
@router.post("/telegram-widget")
|
||||||
async def telegram_widget_auth(request: TelegramWidgetAuth, response: Response):
|
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"""
|
"""Authenticate via Telegram Login Widget"""
|
||||||
print(f"[ModerationAuth] 🔍 Запрос авторизации через Telegram виджет: id={request.id}, username={request.username}")
|
print(f"[ModerationAuth] 🔍 Запрос авторизации через Telegram виджет: id={request.id}, username={request.username}")
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -239,56 +239,79 @@ export default function App() {
|
||||||
if (!telegramApp?.initData && showLoginForm && telegramWidgetRef.current) {
|
if (!telegramApp?.initData && showLoginForm && telegramWidgetRef.current) {
|
||||||
// Глобальная функция для обработки авторизации через виджет
|
// Глобальная функция для обработки авторизации через виджет
|
||||||
window.onTelegramAuth = async (userData) => {
|
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 {
|
try {
|
||||||
setAuthLoading(true);
|
setAuthLoading(true);
|
||||||
|
setError(null);
|
||||||
|
|
||||||
// Отправить данные виджета на сервер для создания сессии
|
// Отправить данные виджета на сервер для создания сессии
|
||||||
const API_URL = getApiUrl();
|
const API_URL = getApiUrl();
|
||||||
// В production используем относительный путь (HTTPS через nginx)
|
// В production используем относительный путь (HTTPS через nginx)
|
||||||
const fullApiUrl = API_URL.startsWith('http') ? API_URL : `${window.location.origin}${API_URL}`;
|
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',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
credentials: 'include',
|
credentials: 'include',
|
||||||
body: JSON.stringify(userData)
|
body: JSON.stringify(userData)
|
||||||
});
|
});
|
||||||
|
|
||||||
|
console.log('[Telegram Widget] Ответ получен:', response.status, response.statusText);
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
const errorData = await response.json().catch(() => ({}));
|
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();
|
const result = await response.json();
|
||||||
|
|
||||||
console.log('[Telegram Widget] Результат авторизации:', result);
|
console.log('[Telegram Widget] ✅ Результат авторизации:', result);
|
||||||
|
|
||||||
if (result.accessToken) {
|
if (result.accessToken) {
|
||||||
localStorage.setItem('moderation_jwt_token', result.accessToken);
|
localStorage.setItem('moderation_jwt_token', result.accessToken);
|
||||||
console.log('[Telegram Widget] Токен сохранен');
|
console.log('[Telegram Widget] ✅ Токен сохранен');
|
||||||
}
|
}
|
||||||
|
|
||||||
if (result?.user) {
|
if (result?.user) {
|
||||||
setUser(result.user);
|
setUser(result.user);
|
||||||
setError(null);
|
setError(null);
|
||||||
console.log('[Telegram Widget] Пользователь установлен:', result.user.username);
|
console.log('[Telegram Widget] ✅ Пользователь установлен:', result.user.username);
|
||||||
|
|
||||||
// Перенаправить на главную страницу после успешной авторизации
|
// Перенаправить на главную страницу после успешной авторизации
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
|
console.log('[Telegram Widget] Перенаправление на главную страницу...');
|
||||||
window.location.href = '/';
|
window.location.href = '/';
|
||||||
}, 500);
|
}, 500);
|
||||||
} else {
|
} else {
|
||||||
|
console.error('[Telegram Widget] ❌ Пользователь не получен от сервера');
|
||||||
throw new Error('Пользователь не получен от сервера');
|
throw new Error('Пользователь не получен от сервера');
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('Ошибка авторизации через виджет:', err);
|
console.error('[Telegram Widget] ❌ Ошибка авторизации через виджет:', err);
|
||||||
|
console.error('[Telegram Widget] Stack:', err.stack);
|
||||||
setError(err.message || 'Ошибка авторизации через Telegram');
|
setError(err.message || 'Ошибка авторизации через Telegram');
|
||||||
} finally {
|
} finally {
|
||||||
setAuthLoading(false);
|
setAuthLoading(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
console.log('[Telegram Widget] ✅ window.onTelegramAuth установлен');
|
||||||
|
|
||||||
const initWidget = () => {
|
const initWidget = () => {
|
||||||
// Проверить не загружен ли уже виджет
|
// Проверить не загружен ли уже виджет
|
||||||
if (document.querySelector('script[src*="telegram-widget"]')) {
|
if (document.querySelector('script[src*="telegram-widget"]')) {
|
||||||
|
|
@ -324,11 +347,23 @@ export default function App() {
|
||||||
console.log('[Telegram Widget] Current origin:', window.location.origin);
|
console.log('[Telegram Widget] Current origin:', window.location.origin);
|
||||||
|
|
||||||
script.onload = () => {
|
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 = () => {
|
script.onerror = (error) => {
|
||||||
console.error('[Telegram Widget] Ошибка загрузки скрипта');
|
console.error('[Telegram Widget] ❌ Ошибка загрузки скрипта:', error);
|
||||||
|
setError('Не удалось загрузить Telegram виджет');
|
||||||
};
|
};
|
||||||
|
|
||||||
widgetContainer.appendChild(script);
|
widgetContainer.appendChild(script);
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue