From 5804775927cde8b1f0593a8e251efaa017907926 Mon Sep 17 00:00:00 2001 From: denis0001-dev Date: Sat, 30 Aug 2025 11:21:24 +0300 Subject: [PATCH] Implement the register screen and make auth work --- frontend/src/auth/api.ts | 6 +- frontend/src/auth/auth.ts | 95 +---------------------- frontend/src/ui/components/Alerts.tsx | 4 +- frontend/src/ui/screen/LoginScreen.tsx | 13 ++-- frontend/src/ui/screen/RegisterScreen.tsx | 10 ++- frontend/src/websocket.ts | 3 +- 6 files changed, 20 insertions(+), 111 deletions(-) diff --git a/frontend/src/auth/api.ts b/frontend/src/auth/api.ts index 2855fb4..1a4812e 100644 --- a/frontend/src/auth/api.ts +++ b/frontend/src/auth/api.ts @@ -1,5 +1,5 @@ import { API_BASE_URL } from "../core/config"; -import { showLogin } from "../navigation"; +// import { showLogin } from "../navigation"; import type { Headers, User, WebSocketMessage } from "../core/types"; import { clearAlerts } from "./auth"; import { request } from "../websocket"; @@ -65,7 +65,7 @@ export function getAuthHeaders(json: boolean = true): Headers { export async function checkAuthStatus(): Promise { // For JWT, we don't have a persistent token on page load // So we'll just show the login form - showLogin(); + // showLogin(); } /** @@ -83,6 +83,6 @@ export async function logout(): Promise { currentUser = null; authToken = null; - showLogin(); + // showLogin(); clearAlerts(); } \ No newline at end of file diff --git a/frontend/src/auth/auth.ts b/frontend/src/auth/auth.ts index d2ef220..e37fa40 100644 --- a/frontend/src/auth/auth.ts +++ b/frontend/src/auth/auth.ts @@ -5,9 +5,6 @@ * @version 1.0.0 */ -import type { ErrorResponse, RegisterRequest } from "../core/types"; -import { API_BASE_URL } from "../core/config"; -import { showLogin } from "../navigation"; import { id } from "../utils/utils"; /** @@ -17,94 +14,4 @@ import { id } from "../utils/utils"; export function clearAlerts(): void { id('login-alerts').innerHTML = ''; id('register-alerts').innerHTML = ''; -} - -/** - * Shows an alert message in the specified container - * @param {string} containerId - ID of the container to show the alert in - * @param {string} message - Alert message to display - * @param {'success' | 'danger'} type - Type of alert (success or danger) - */ -export function showAlert(containerId: string, message: string, type: "success" | "danger" = 'danger'): void { - const container = id(containerId); - const alertDiv = document.createElement('div'); - alertDiv.className = `alert alert-${type}`; - alertDiv.textContent = message; - container.appendChild(alertDiv); -} - -/** - * Handles registration form submission - * @param {Event} e - Form submission event - * @private - */ -async function handleRegister(e: Event): Promise { - e.preventDefault(); - - const usernameElement = id('register-username'); - const passwordElement = id('register-password'); - const confirmPasswordElement = id('register-confirm-password'); - - const username = usernameElement.value.trim(); - const password = passwordElement.value.trim(); - const confirmPassword = confirmPasswordElement.value.trim(); - - if (!username || !password || !confirmPassword) { - showAlert('register-alerts', 'Пожалуйста, заполните все поля', 'danger'); - return; - } - - if (password !== confirmPassword) { - showAlert('register-alerts', 'Пароли не совпадают', 'danger'); - return; - } - - if (username.length < 3 || username.length > 20) { - showAlert('register-alerts', 'Имя пользователя должно быть от 3 до 20 символов', 'danger'); - return; - } - - if (password.length < 5 || password.length > 50) { - showAlert('register-alerts', 'Пароль должен быть от 5 до 50 символов', 'danger'); - return; - } - - try { - const request: RegisterRequest = { - username: username, - password: password, - confirm_password: confirmPassword - } - - const response = await fetch(`${API_BASE_URL}/register`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify(request) - }); - - if (response.ok) { - // Registration successful - showAlert('register-alerts', 'Регистрация прошла успешно! Теперь вы можете войти.', 'success'); - setTimeout(() => { - showLogin(); - }, 2000); - } else { - const data: ErrorResponse = await response.json(); - showAlert('register-alerts', data.message || 'Ошибка при регистрации', 'danger'); - } - } catch (error) { - showAlert('register-alerts', 'Ошибка соединения с сервером', 'danger'); - } -} - -/** - * Initializes authentication functionality - * @private - */ -function init(): void { - id('register-form-element').addEventListener('submit', handleRegister); -} - -init(); \ No newline at end of file +} \ No newline at end of file diff --git a/frontend/src/ui/components/Alerts.tsx b/frontend/src/ui/components/Alerts.tsx index fccc0d4..3284ac3 100644 --- a/frontend/src/ui/components/Alerts.tsx +++ b/frontend/src/ui/components/Alerts.tsx @@ -8,8 +8,8 @@ export interface Alert { export function AlertsContainer({ alerts }: { alerts: Alert[]}) { return (
- {alerts.map(alert => { - return
{alert.message}
+ {alerts.slice(-3).map((alert, i) => { + return
{alert.message}
})}
) diff --git a/frontend/src/ui/screen/LoginScreen.tsx b/frontend/src/ui/screen/LoginScreen.tsx index cf95ec2..24a3cbd 100644 --- a/frontend/src/ui/screen/LoginScreen.tsx +++ b/frontend/src/ui/screen/LoginScreen.tsx @@ -1,20 +1,21 @@ import { useImmer } from "use-immer"; -import { showChat, showRegister } from "../../navigation"; import { AlertsContainer, type Alert, type AlertType } from "../components/Alerts"; import { AuthContainer, AuthHeader } from "../components/Auth"; import type { ErrorResponse, LoginRequest, LoginResponse } from "../../core/types"; import { setUser } from "../../auth/api"; import { ensureKeysOnLogin } from "../../auth/crypto"; import { API_BASE_URL } from "../../core/config"; -import { initializeProfile } from "../../userPanel/profile/profile"; +// import { initializeProfile } from "../../userPanel/profile/profile"; import { useRef } from "react"; import type { TextField } from "mdui/components/text-field"; +import { useAppState } from "../state"; export default function LoginScreen() { const [alerts, updateAlerts] = useImmer([]); + const setCurrentPage = useAppState(state => state.setCurrentPage); function showAlert(type: AlertType, message: string) { - updateAlerts((alerts) => alerts.push({type: type, message: message})); + updateAlerts((alerts) => { alerts.push({type: type, message: message}) }); } const usernameElement = useRef(null); @@ -61,8 +62,8 @@ export default function LoginScreen() { } catch (e) { console.error("Key setup failed:", e); } - showChat(); - initializeProfile(); // Initialize profile after login + setCurrentPage("chat"); + // initializeProfile(); // Initialize profile after login } else { const data: ErrorResponse = await response.json(); showAlert("danger", data.message || "Неверное имя пользователя или пароль"); @@ -103,7 +104,7 @@ export default function LoginScreen() { + onClick={() => setCurrentPage("register")}> Зарегистрируйтесь

diff --git a/frontend/src/ui/screen/RegisterScreen.tsx b/frontend/src/ui/screen/RegisterScreen.tsx index ecc8f77..2dc5a82 100644 --- a/frontend/src/ui/screen/RegisterScreen.tsx +++ b/frontend/src/ui/screen/RegisterScreen.tsx @@ -1,5 +1,5 @@ import { useImmer } from "use-immer"; -import { showLogin } from "../../navigation"; +// import { showLogin } from "../../navigation"; import { AuthContainer, AuthHeader } from "../components/Auth"; import { AlertsContainer, type Alert, type AlertType } from "../components/Alerts"; import { useRef } from "react"; @@ -7,12 +7,14 @@ import { TextField } from "mdui/components/text-field"; import type { ErrorResponse, RegisterRequest } from "../../core/types"; import { API_BASE_URL } from "../../core/config"; import { delay } from "../../utils/utils"; +import { useAppState } from "../state"; export default function RegisterScreen() { const [alerts, updateAlerts] = useImmer([]); + const setCurrentPage = useAppState(state => state.setCurrentPage); function showAlert(type: AlertType, message: string) { - updateAlerts((alerts) => alerts.push({type: type, message: message})); + updateAlerts((alerts) => { alerts.push({type: type, message: message}) }); } const usernameElement = useRef(null); @@ -71,7 +73,7 @@ export default function RegisterScreen() { // Registration successful showAlert("success", "Регистрация прошла успешно! Теперь вы можете войти."); await delay(2000); - showLogin(); + setCurrentPage("login"); } else { const data: ErrorResponse = await response.json(); showAlert("danger", data.message || "Ошибка при регистрации"); @@ -127,7 +129,7 @@ export default function RegisterScreen() { href="#" id="login-link" className="link" - onClick={showLogin}> + onClick={() => setCurrentPage("login")}> Войдите

diff --git a/frontend/src/websocket.ts b/frontend/src/websocket.ts index afd28a2..54dcf3b 100644 --- a/frontend/src/websocket.ts +++ b/frontend/src/websocket.ts @@ -5,7 +5,6 @@ * @version 1.0.0 */ -import { handleWebSocketMessage } from "./chat/chat"; import { API_WS_BASE_URL } from "./core/config"; import type { WebSocketMessage } from "./core/types"; import { delay } from "./utils/utils"; @@ -71,6 +70,6 @@ async function onError() { // -------------- websocket.addEventListener("message", (e) => { - handleWebSocketMessage(JSON.parse(e.data)); + // handleWebSocketMessage(JSON.parse(e.data)); }); websocket.addEventListener("error", onError); \ No newline at end of file