From 648613e24c8afe5fd3c599def61b33ccf7bcb96c Mon Sep 17 00:00:00 2001
From: nsfisis <nsfisis@gmail.com>
Date: Mon, 29 Jul 2024 20:04:03 +0900
Subject: feat: authenticate WebSocket connection by short-lived access token

---
 frontend/app/routes/golf.$gameId.play.tsx | 49 ++++++++++++++++++++++---------
 1 file changed, 35 insertions(+), 14 deletions(-)

(limited to 'frontend/app/routes/golf.$gameId.play.tsx')

diff --git a/frontend/app/routes/golf.$gameId.play.tsx b/frontend/app/routes/golf.$gameId.play.tsx
index bda563f..78ce585 100644
--- a/frontend/app/routes/golf.$gameId.play.tsx
+++ b/frontend/app/routes/golf.$gameId.play.tsx
@@ -8,26 +8,47 @@ export async function loader({ params, request }: LoaderFunctionArgs) {
   const { token } = await isAuthenticated(request, {
     failureRedirect: "/login",
   });
-  const { data, error } = await apiClient.GET("/games/{game_id}", {
-    params: {
-      path: {
-        game_id: Number(params.gameId),
+
+  const fetchGame = async () => {
+    const { data, error } = await apiClient.GET("/games/{game_id}", {
+      params: {
+        path: {
+          game_id: Number(params.gameId),
+        },
+        header: {
+          Authorization: `Bearer ${token}`,
+        },
       },
-      header: {
-        Authorization: `Bearer ${token}`,
+    });
+    if (error) {
+      throw new Error(error.message);
+    }
+    return data;
+  };
+
+  const fetchSockToken = async () => {
+    const { data, error } = await apiClient.GET("/token", {
+      params: {
+        header: {
+          Authorization: `Bearer ${token}`,
+        },
       },
-    },
-  });
-  if (error) {
-    throw new Error(error.message);
-  }
+    });
+    if (error) {
+      throw new Error(error.message);
+    }
+    return data.token;
+  };
+
+  const [game, sockToken] = await Promise.all([fetchGame(), fetchSockToken()]);
   return {
-    game: data,
+    game,
+    sockToken,
   };
 }
 
 export default function GolfPlay() {
-  const { game } = useLoaderData<typeof loader>();
+  const { game, sockToken } = useLoaderData<typeof loader>();
 
-  return <GolfPlayApp game={game} />;
+  return <GolfPlayApp game={game} sockToken={sockToken} />;
 }
-- 
cgit v1.2.3-70-g09d2

