From bb6aa7ab1268a202c19732fa71b3d49ed61586ef Mon Sep 17 00:00:00 2001 From: Tristan Teufel Date: Tue, 2 Jan 2024 07:31:26 +0100 Subject: [PATCH] add protected routes --- src/app/Login.tsx | 17 ++++++++---- src/main.tsx | 5 ---- src/router.tsx | 67 +++++++++++++++++++++++++++++++++++++++-------- 3 files changed, 68 insertions(+), 21 deletions(-) diff --git a/src/app/Login.tsx b/src/app/Login.tsx index ef25c93..ad736ce 100644 --- a/src/app/Login.tsx +++ b/src/app/Login.tsx @@ -17,17 +17,24 @@ export const Login = () => { const username = d.currentTarget['username'].value; const password = d.currentTarget['password'].value; const response = await loginMutation.mutateAsync({ username, password }); - if(response) { + if (response) { navigateRooms(); } }; return ( - - {t('signInTitle')} - - {loginMutation.isError && {t('errorOccuredWhileLogin')}} + + {t('signInTitle')} + + {loginMutation.isError && ( + + + {t('errorOccuredWhileLogin')} + {(loginMutation.error as Error).message} + + + )}
- - ); diff --git a/src/router.tsx b/src/router.tsx index 716e97c..47d188e 100644 --- a/src/router.tsx +++ b/src/router.tsx @@ -1,14 +1,59 @@ -import { Routes, Route } from "react-router-dom"; -import { Login } from './app/Login' -import { Room } from "./app/Room"; -import { Rooms } from './app/Rooms' +import { + createBrowserRouter, + RouterProvider, + useNavigate, +} from 'react-router-dom'; +import { Login } from './app/Login'; +import { Room } from './app/Room'; +import { Rooms } from './app/Rooms'; +import { ReactNode, useEffect } from 'react'; +import { getSessionId } from './hooks/useApi'; + +interface ProtectedRouteProps { + children: ReactNode; +} + +const ProtectedRoute = ({ children }: ProtectedRouteProps) => { + const navigate = useNavigate(); + const sessionId = getSessionId(); + + useEffect(() => { + if (!sessionId) { + navigate('/'); + } + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [sessionId]); + + return children; +}; export const Router = () => { + const basename = process.env.NODE_ENV === 'production' ? '/addons/mui/' : '/'; + const router = createBrowserRouter( + [ + { + path: '/', + element: , + }, + { + path: '/room/:roomId', + element: ( + + + + ), + }, + { + path: '/rooms', + element: ( + + + + ), + }, + ], + { basename } + ); - return ( - - } /> - } /> - } /> - ) -} \ No newline at end of file + return ; +};