128 lines
6.4 KiB
JavaScript
128 lines
6.4 KiB
JavaScript
// /public/js/auth.js
|
||
|
||
// Эта функция будет вызвана из main.js и получит необходимые зависимости
|
||
export function initAuth(dependencies) {
|
||
const { socket, clientState, ui } = dependencies;
|
||
const { loginForm, registerForm, logoutButton } = ui.elements; // Получаем нужные DOM элементы
|
||
|
||
// --- Обработчики событий DOM ---
|
||
if (registerForm) {
|
||
registerForm.addEventListener('submit', (e) => {
|
||
e.preventDefault();
|
||
const usernameInput = document.getElementById('register-username');
|
||
const passwordInput = document.getElementById('register-password');
|
||
if (!usernameInput || !passwordInput) return;
|
||
|
||
const username = usernameInput.value;
|
||
const password = passwordInput.value;
|
||
|
||
// Блокируем кнопки на время запроса
|
||
const regButton = registerForm.querySelector('button');
|
||
const loginButton = loginForm ? loginForm.querySelector('button') : null;
|
||
if (regButton) regButton.disabled = true;
|
||
if (loginButton) loginButton.disabled = true;
|
||
|
||
ui.setAuthMessage('Регистрация...');
|
||
socket.emit('register', { username, password });
|
||
});
|
||
}
|
||
|
||
if (loginForm) {
|
||
loginForm.addEventListener('submit', (e) => {
|
||
e.preventDefault();
|
||
const usernameInput = document.getElementById('login-username');
|
||
const passwordInput = document.getElementById('login-password');
|
||
if (!usernameInput || !passwordInput) return;
|
||
|
||
const username = usernameInput.value;
|
||
const password = passwordInput.value;
|
||
|
||
// Блокируем кнопки на время запроса
|
||
const loginButton = loginForm.querySelector('button');
|
||
const regButton = registerForm ? registerForm.querySelector('button') : null;
|
||
if (loginButton) loginButton.disabled = true;
|
||
if (regButton) regButton.disabled = true;
|
||
|
||
ui.setAuthMessage('Вход...');
|
||
socket.emit('login', { username, password });
|
||
});
|
||
}
|
||
|
||
if (logoutButton) {
|
||
logoutButton.addEventListener('click', () => {
|
||
logoutButton.disabled = true;
|
||
socket.emit('logout');
|
||
|
||
// Обновляем состояние клиента немедленно, не дожидаясь ответа сервера (опционально)
|
||
clientState.isLoggedIn = false;
|
||
clientState.loggedInUsername = '';
|
||
clientState.myUserId = null;
|
||
// isInGame и другие игровые переменные сбросятся в ui.showAuthScreen()
|
||
// disableGameControls() также будет вызван опосредованно через showAuthScreen -> resetGameVariables
|
||
|
||
ui.showAuthScreen(); // Показываем экран логина
|
||
ui.setGameStatusMessage("Вы вышли из системы."); // Используем gameStatusMessage для общего статуса после выхода
|
||
// ui.setAuthMessage("Вы вышли из системы."); // или authMessage, если он виден
|
||
// Кнопка разблокируется при следующем показе userInfoDiv или можно здесь
|
||
// logoutButton.disabled = false; // но лучше, чтобы UI сам управлял этим при показе
|
||
});
|
||
}
|
||
|
||
// --- Обработчики событий Socket.IO ---
|
||
socket.on('registerResponse', (data) => {
|
||
ui.setAuthMessage(data.message, !data.success);
|
||
if (data.success && registerForm) {
|
||
registerForm.reset(); // Очищаем форму при успехе
|
||
}
|
||
// Разблокируем кнопки
|
||
if (registerForm) {
|
||
const regButton = registerForm.querySelector('button');
|
||
if (regButton) regButton.disabled = false;
|
||
}
|
||
if (loginForm) {
|
||
const loginButton = loginForm.querySelector('button');
|
||
if (loginButton) loginButton.disabled = false;
|
||
}
|
||
});
|
||
|
||
socket.on('loginResponse', (data) => {
|
||
if (data.success) {
|
||
clientState.isLoggedIn = true;
|
||
clientState.loggedInUsername = data.username;
|
||
clientState.myUserId = data.userId;
|
||
|
||
ui.setAuthMessage(""); // Очищаем сообщение об аутентификации
|
||
ui.showGameSelectionScreen(data.username); // Показываем экран выбора игры
|
||
// Запрос gameState при успешном логине и реконнекте теперь обрабатывается в main.js
|
||
// если пользователь уже был залогинен при 'connect'
|
||
} else {
|
||
clientState.isLoggedIn = false;
|
||
clientState.loggedInUsername = '';
|
||
clientState.myUserId = null;
|
||
ui.setAuthMessage(data.message, true); // Показываем ошибку
|
||
}
|
||
// Разблокируем кнопки
|
||
if (registerForm) {
|
||
const regButton = registerForm.querySelector('button');
|
||
if (regButton) regButton.disabled = false;
|
||
}
|
||
if (loginForm) {
|
||
const loginButton = loginForm.querySelector('button');
|
||
if (loginButton) loginButton.disabled = false;
|
||
}
|
||
// Убедимся, что кнопка logout активна, если пользователь успешно вошел
|
||
if (logoutButton && clientState.isLoggedIn) {
|
||
logoutButton.disabled = false;
|
||
}
|
||
});
|
||
|
||
// Примечание: событие 'logout' от сервера обычно не требует специального обработчика здесь,
|
||
// так как клиент сам инициирует выход и обновляет UI.
|
||
// Если сервер принудительно разлогинивает, то такой обработчик может понадобиться.
|
||
// socket.on('forceLogout', (data) => {
|
||
// clientState.isLoggedIn = false;
|
||
// // ...
|
||
// ui.showAuthScreen();
|
||
// ui.setAuthMessage(data.message || "Вы были разлогинены сервером.");
|
||
// });
|
||
} |