import { useState } from "react"; const API_BASE = "http://localhost:8080/api/v1"; function basicAuthorization(username, password) { const encoded = btoa( new TextEncoder() .encode(`${username}:${password}`) .reduce((value, byte) => value + String.fromCharCode(byte), "") ); return `Basic ${encoded}`; } async function apiFetch( path, { method = "GET", token, basicCredentials, body, } = {} ) { const headers = { Accept: "application/json", }; if (body !== undefined) { headers["Content-Type"] = "application/json"; } if (token) { headers.Authorization = `Bearer ${token}`; } if (basicCredentials) { headers.Authorization = basicAuthorization( basicCredentials.username, basicCredentials.password ); } const response = await fetch(`${API_BASE}${path}`, { method, headers, body: body !== undefined ? JSON.stringify(body) : undefined, }); const requestId = response.headers.get("X-Request-Id"); const raw = await response.text(); const data = raw ? JSON.parse(raw) : null; if (!response.ok) { const message = data?.error?.message || `HTTP ${response.status}`; throw new Error(`${message} (request_id: ${requestId || "unknown"})`); } return data; } export default function App() { const [username, setUsername] = useState(""); const [displayName, setDisplayName] = useState(""); const [password, setPassword] = useState(""); const [session, setSession] = useState(null); const [chat, setChat] = useState(null); const [memberIdsInput, setMemberIdsInput] = useState(""); const [chatTitle, setChatTitle] = useState(""); const [text, setText] = useState(""); const [messages, setMessages] = useState([]); const [error, setError] = useState(""); const [loading, setLoading] = useState(false); const me = session?.user ?? null; const token = session?.token ?? null; async function handleRegister() { setError(""); setLoading(true); try { await apiFetch("/users", { method: "POST", body: { username, display_name: displayName, password, }, }); const createdSession = await apiFetch("/auth/sessions", { method: "POST", basicCredentials: { username, password, }, }); setSession(createdSession); setPassword(""); } catch (requestError) { setError(requestError.message); } finally { setLoading(false); } } async function handleCreateChat() { if (!me || !token) { return; } setError(""); setLoading(true); try { const enteredMemberIds = memberIdsInput .split(",") .map((value) => value.trim()) .filter(Boolean); const uniqueMemberIds = [...new Set([me.id, ...enteredMemberIds])]; const created = await apiFetch("/chats", { method: "POST", token, body: { title: chatTitle, member_ids: uniqueMemberIds, }, }); setChat(created); setMessages([]); setText(""); } catch (requestError) { setError(requestError.message); } finally { setLoading(false); } } async function handleSendMessage() { if (!chat || !token) { return; } setError(""); setLoading(true); try { const message = await apiFetch(`/chats/${chat.id}/messages`, { method: "POST", token, body: { text }, }); setMessages((previous) => [...previous, message]); setText(""); } catch (requestError) { setError(requestError.message); } finally { setLoading(false); } } async function handleLoadHistory() { if (!chat || !token) { return; } setError(""); setLoading(true); try { const page = await apiFetch(`/chats/${chat.id}/messages?limit=100`, { token, }); setMessages(page.items); } catch (requestError) { setError(requestError.message); } finally { setLoading(false); } } async function handleLogout() { if (!token) { return; } setError(""); setLoading(true); try { await apiFetch("/auth/sessions/current", { method: "DELETE", token, }); setSession(null); setChat(null); setMessages([]); setText(""); setMemberIdsInput(""); setChatTitle(""); } catch (requestError) { setError(requestError.message); // Если token уже истёк или был отозван, локальная сессия всё равно // недействительна, поэтому её следует очистить. if ( requestError.message.includes("Authentication") || requestError.message.includes("401") ) { setSession(null); setChat(null); setMessages([]); } } finally { setLoading(false); } } return (

Lab2 Messenger — демо-клиент

{error && (

{error}

)} {!me && (

Регистрация и вход

После регистрации клиент автоматически создаст сессию через Basic authentication и начнёт использовать Bearer-token.

setUsername(event.target.value)} autoComplete="username" /> setDisplayName(event.target.value)} autoComplete="name" /> setPassword(event.target.value)} autoComplete="new-password" />
)} {me && !chat && (

Вошли как {me.username}

ID пользователя: {me.id}

Создать чат

setChatTitle(event.target.value)} /> setMemberIdsInput(event.target.value)} />
)} {me && chat && (

Вошли как {me.username}

Чат: {chat.title}

Участники: {chat.member_ids.length}

setText(event.target.value)} />
)}
); }