From 3e6d2390e6f6ce4f5844a17558376ae9a99b6475 Mon Sep 17 00:00:00 2001 From: Araozu Date: Wed, 8 May 2024 13:50:25 -0500 Subject: [PATCH] Validate stored id with the backend --- src/pages/Index.tsx | 54 ++++++++++++++++++++++++++++++++++++++++----- src/utils.ts | 2 +- 2 files changed, 50 insertions(+), 6 deletions(-) diff --git a/src/pages/Index.tsx b/src/pages/Index.tsx index 9a8229b..03012e7 100644 --- a/src/pages/Index.tsx +++ b/src/pages/Index.tsx @@ -9,11 +9,41 @@ const usernameKey = "Username"; export function Index() { const [userInfo, setUserInfo] = createSignal(null); + const [validated, setValidated] = createSignal(false); - onMount(() => { + onMount(async() => { // attempt to get userinfo from localstorage // validate userinfo with backend - console.log("validating userinfo in localstorage"); + const UserId = localStorage.getItem(userIdKey); + const Username = localStorage.getItem(usernameKey); + + if (UserId === null || Username === null) { + return; + } + + setUserInfo({ + UserId, + Username, + }); + setValidated(false); + + try { + // validate in backend + await backend.get("/validate", { + headers: { + "Authorization": `Bearer ${UserId}`, + }, + }); + + // If the previous hasn't throw, the token is valid. + setValidated(true); + } catch (e) { + // If this throws, the userid is not validated + localStorage.removeItem(userIdKey); + localStorage.removeItem(usernameKey); + setUserInfo(null); + setValidated(false); + } }); return ( @@ -26,10 +56,17 @@ export function Index() {

Play:

- + { + setValidated(true); + setUserInfo(i); + }} + /> - -

:D (user registered)

+ +

Validating user id...

+
+ +

@@ -124,3 +161,10 @@ function UserRegistration(props: {setUserInfo: (u: UserInfo) => void}) { ); } +function LobbyConnection() { + return ( +
+ Lobby creation :D +
+ ); +} diff --git a/src/utils.ts b/src/utils.ts index ecd9c9f..d201e50 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -5,7 +5,7 @@ export const backend = axios.create({ }); export type UserInfo = { - UserId: number, + UserId: string, Username: string, }