From 800fa62ec6047c286cd49a8bb1327bd9a926d1ee Mon Sep 17 00:00:00 2001 From: Araozu Date: Sat, 25 May 2024 16:26:29 -0500 Subject: [PATCH] Authenticate with the server --- src/pages/Lobby.tsx | 51 ++++++++++++++++++++++++++++++++++++++------- 1 file changed, 43 insertions(+), 8 deletions(-) diff --git a/src/pages/Lobby.tsx b/src/pages/Lobby.tsx index b42dd70..9d355f3 100644 --- a/src/pages/Lobby.tsx +++ b/src/pages/Lobby.tsx @@ -1,6 +1,7 @@ import { Show, createSignal, onCleanup, onMount } from "solid-js"; import LoadingIcon from "../assets/loading.svg"; import ErrorIcon from "../assets/error.svg"; +import ConnectedIcon from "../assets/ok.svg"; import { userIdKey } from "./Index"; import { useNavigate } from "@solidjs/router"; @@ -12,6 +13,11 @@ enum LobbyStatus { Error, } +type LobbyMsg = { + action: string, + value: string, +} + const connectionRetryInterval = 5000; export function Lobby() { @@ -31,20 +37,21 @@ export function Lobby() { }; const onWsOpen = () => { - console.log("Connection open!"); - setStatus(LobbyStatus.Connected); + console.log("Connection open. Authenticating..."); + setStatus(LobbyStatus.Authenticating); // The first message must be authenticating with the server const userId = localStorage.getItem(userIdKey); if (userId === null) { // Redirect to home page - ws?.close(); + ws?.close(1000); navigate("/"); return; } // Send an auth message to the server + // The server will respond with either "authenticated" or "unauthenticated" ws!.send(JSON.stringify({ action: "auth", value: userId, @@ -52,8 +59,19 @@ export function Lobby() { }; const onWsMessage = (ev: MessageEvent) => { - console.log("message from ws!"); - console.log(ev.data); + const data = JSON.parse(ev.data) as LobbyMsg; + + switch (data.action) { + case "auth": { + if (data.value === "authenticated") { + setStatus(LobbyStatus.Connected); + } else if (data.value === "unauthenticated") { + ws?.close(1000); + navigate("/"); + } + break; + } + } }; const onWsError = (ev: Event) => { @@ -62,7 +80,12 @@ export function Lobby() { setStatus(LobbyStatus.Error); }; - const onWsClose = () => { + const onWsClose = (ev: CloseEvent) => { + if (ev.code === 1000) { + // The connection was normally closed + return; + } + // If the previous state is "Error", we don't set // the state to Disconnected if (status() !== LobbyStatus.Error) { @@ -85,7 +108,8 @@ export function Lobby() { onMount(lobbyConnect); onCleanup(() => { - ws?.close(); + console.log("lobby cleanup"); + ws?.close(1000); }); return ( @@ -94,6 +118,12 @@ export function Lobby() { Lobby + +

+ ... + Disconected. Attempting reconnection in {connectionRetryInterval / 1000} seconds. +

+

... @@ -103,7 +133,7 @@ export function Lobby() {

... - Logging in to the server + Authenticating with the server

@@ -115,6 +145,11 @@ export function Lobby() { +

+ ... + Connected +

+