From 709bc96e57db0625120ab09c39323f775a1c485a Mon Sep 17 00:00:00 2001 From: DTieman Date: Fri, 7 Apr 2023 12:13:07 +0200 Subject: [PATCH] auth --- src/index.tsx | 15 ++++++++----- src/layout/pages/MainLobby.tsx | 4 ++-- src/utils/contexts/AuthContext.tsx | 36 ++++++++++++++++++++++++++++++ 3 files changed, 47 insertions(+), 8 deletions(-) create mode 100644 src/utils/contexts/AuthContext.tsx diff --git a/src/index.tsx b/src/index.tsx index be8d0d4..2bcefd5 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -2,14 +2,17 @@ import React from 'react'; import ReactDOM from 'react-dom/client'; import App from './App'; import ThemeContextProvider from "./utils/contexts/ThemeContext"; +import AuthContextProvider from "./utils/contexts/AuthContext"; const root = ReactDOM.createRoot( - document.getElementById('root') as HTMLElement + document.getElementById('root') as HTMLElement ); root.render( - - - - - + + + + + + + ); \ No newline at end of file diff --git a/src/layout/pages/MainLobby.tsx b/src/layout/pages/MainLobby.tsx index 46c2cee..5a0910b 100644 --- a/src/layout/pages/MainLobby.tsx +++ b/src/layout/pages/MainLobby.tsx @@ -14,8 +14,8 @@ const MainLobby = () => { const handleCreateRoom = () => { fetch(ROOM_URL, { method: 'POST', - }).then(r => r.json()).then(data => { - navigateTo(`/room/${data}`) + }).then(res => res.json()).then(room => { + navigateTo(`/room/${room}`); }); } diff --git a/src/utils/contexts/AuthContext.tsx b/src/utils/contexts/AuthContext.tsx new file mode 100644 index 0000000..c1b21bc --- /dev/null +++ b/src/utils/contexts/AuthContext.tsx @@ -0,0 +1,36 @@ +import React from "react"; + +const AUTH_URL = `http://${process.env.REACT_APP_API_URL}/auth`; + +interface IAuthContext { + sessionToken: string +} + +const AuthContext = React.createContext({ + sessionToken: '' +}); + +export const useAuth = () => React.useContext(AuthContext); + +const AuthContextProvider = ({children}: any) => { + const [sessionToken] = React.useState(''); + + React.useEffect(() => { + const token = window.localStorage.getItem('session_token'); + if (!token) { + fetch(AUTH_URL, { + method: 'GET' + }).then(res => res.json()).then(token => { + window.localStorage.setItem('session_token', token); + }); + } + }, []); + + return ( + + {children} + + ); +}; + +export default AuthContextProvider; \ No newline at end of file