From b0b7e1ad2d996e5fedb71f1663170ee1d55a4ce9 Mon Sep 17 00:00:00 2001 From: pajowu Date: Mon, 18 Sep 2023 18:44:31 +0200 Subject: [PATCH] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20Rework=20auth=20in=20route?= =?UTF-8?q?r?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes #362 --- frontend/src/app.tsx | 55 +++++++++++++++++++++++++------------------- 1 file changed, 31 insertions(+), 24 deletions(-) diff --git a/frontend/src/app.tsx b/frontend/src/app.tsx index 50a786b1..cec51625 100644 --- a/frontend/src/app.tsx +++ b/frontend/src/app.tsx @@ -1,4 +1,4 @@ -import { Redirect, Route, Router, Switch, useLocation } from 'wouter'; +import { DefaultParams, Route, RouteProps, Router, Switch, useLocation } from 'wouter'; import { trimTrailingSlash } from './utils/trim_trailing_slash'; import { LoginPage } from './pages/login'; @@ -16,17 +16,35 @@ import { AboutPage } from './pages/about'; registerCopyHandler(); -const LOCATIONS_WIHTOUT_AUTH = ['/about']; +export function AuthenticatedRoute({ + ...props +}: RouteProps) { + const [_, navigate] = useLocation(); + const { isLoggedIn, hasShareToken, isLoading } = useAuthData(); + const isAuthenticated = isLoggedIn || hasShareToken; + if (!isAuthenticated && !isLoading) { + navigate('/login'); + return null; + } + return ; +} + +export function LoggedInRoute({ + ...props +}: RouteProps) { + const [_, navigate] = useLocation(); + const { isLoggedIn, isLoading } = useAuthData(); + if (!isLoggedIn && !isLoading) { + navigate('/login'); + return null; + } + return ; +} export function App() { const routerBase = trimTrailingSlash(import.meta.env.BASE_URL); - const [location, navigate] = useLocation(); - const { isLoading, isLoggedIn, hasShareToken } = useAuthData(); - const isAuthenticated = isLoggedIn || hasShareToken; - if (!isAuthenticated && !isLoading && !LOCATIONS_WIHTOUT_AUTH.includes(location)) { - setTimeout(() => navigate('/login'), 0); - } + const { isLoading } = useAuthData(); return ( @@ -37,22 +55,11 @@ export function App() { - {isLoggedIn && ( - <> - - - - )} - - {(isLoggedIn || hasShareToken) && ( - - )} - {/* If the user has a share token, but is not logged in, we redirect them to the login page instead of showing a 404 */} - {hasShareToken && !isLoggedIn && ( - - - - )} + + + + + {isLoading && }