Skip to content

Commit

Permalink
♻️ Rework auth in router
Browse files Browse the repository at this point in the history
Closes #362
  • Loading branch information
pajowu committed Sep 18, 2023
1 parent e4633a2 commit b0b7e1a
Showing 1 changed file with 31 additions and 24 deletions.
55 changes: 31 additions & 24 deletions frontend/src/app.tsx
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -16,17 +16,35 @@ import { AboutPage } from './pages/about';

registerCopyHandler();

const LOCATIONS_WIHTOUT_AUTH = ['/about'];
export function AuthenticatedRoute<T extends DefaultParams = DefaultParams>({
...props
}: RouteProps<T>) {
const [_, navigate] = useLocation();
const { isLoggedIn, hasShareToken, isLoading } = useAuthData();
const isAuthenticated = isLoggedIn || hasShareToken;
if (!isAuthenticated && !isLoading) {
navigate('/login');
return null;
}
return <Route {...props} />;
}

export function LoggedInRoute<T extends DefaultParams = DefaultParams>({
...props
}: RouteProps<T>) {
const [_, navigate] = useLocation();
const { isLoggedIn, isLoading } = useAuthData();
if (!isLoggedIn && !isLoading) {
navigate('/login');
return null;
}
return <Route {...props} />;
}

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 (
<Router base={routerBase}>
Expand All @@ -37,22 +55,11 @@ export function App() {
<Route path="/page/:pageId" component={PagePage} />
<Route path="/about" component={AboutPage} />

{isLoggedIn && (
<>
<Route path="/" component={UserHomePage} />
<Route path="/new" component={NewDocumentPage} />
</>
)}

{(isLoggedIn || hasShareToken) && (
<Route path="/document/:documentId" component={DocumentPage} />
)}
{/* 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 && (
<Route>
<Redirect to="/login" />
</Route>
)}
<LoggedInRoute path="/" component={UserHomePage} />
<LoggedInRoute path="/new" component={NewDocumentPage} />

<AuthenticatedRoute path="/document/:documentId" component={DocumentPage} />

{isLoading && <Route component={LoadingPage} />}
<Route component={PageNotFoundPage} />
</Switch>
Expand Down

0 comments on commit b0b7e1a

Please sign in to comment.