Skip to content

Commit a281c68

Browse files
committed
React-supabase-todolist: Added auth guard to pages that require a session.
1 parent 3f8f748 commit a281c68

File tree

1 file changed

+42
-5
lines changed

1 file changed

+42
-5
lines changed

demos/react-supabase-todolist/src/app/router.tsx

Lines changed: 42 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,53 @@
1-
import { Outlet, createBrowserRouter } from 'react-router-dom';
1+
import { Outlet, createBrowserRouter, useNavigate } from 'react-router-dom';
22
import LoginPage from '@/app/auth/login/page';
33
import RegisterPage from '@/app/auth/register/page';
44
import EntryPage from '@/app/page';
55
import TodoEditPage from '@/app/views/todo-lists/edit/page';
66
import TodoListsPage from '@/app/views/todo-lists/page';
77
import ViewsLayout from '@/app/views/layout';
88
import SQLConsolePage from '@/app/views/sql-console/page';
9+
import { useSupabase } from '@/components/providers/SystemProvider';
10+
import React from 'react';
911

1012
export const TODO_LISTS_ROUTE = '/views/todo-lists';
1113
export const TODO_EDIT_ROUTE = '/views/todo-lists/:id';
1214
export const LOGIN_ROUTE = '/auth/login';
1315
export const REGISTER_ROUTE = '/auth/register';
1416
export const SQL_CONSOLE_ROUTE = '/sql-console';
1517

18+
interface AuthGuardProps {
19+
children: JSX.Element;
20+
}
21+
22+
const AuthGuard = ({ children }: AuthGuardProps) => {
23+
const connector = useSupabase()
24+
25+
const navigate = useNavigate();
26+
React.useEffect(() => {
27+
if (!connector) {
28+
console.error(`No Supabase connector has been created yet.`);
29+
return;
30+
}
31+
const loginGuard = () => {
32+
if (!connector.currentSession) {
33+
navigate(LOGIN_ROUTE);
34+
}
35+
}
36+
if (connector.ready) {
37+
loginGuard();
38+
} else {
39+
const l = connector.registerListener({
40+
initialized: () => {
41+
loginGuard();
42+
}
43+
});
44+
return () => l?.();
45+
}
46+
47+
}, []);
48+
return children;
49+
};
50+
1651
/**
1752
* Navigate to this route after authentication
1853
*/
@@ -33,9 +68,11 @@ export const router = createBrowserRouter([
3368
},
3469
{
3570
element: (
36-
<ViewsLayout>
37-
<Outlet />
38-
</ViewsLayout>
71+
<AuthGuard>
72+
<ViewsLayout>
73+
<Outlet />
74+
</ViewsLayout>
75+
</AuthGuard>
3976
),
4077
children: [
4178
{
@@ -52,4 +89,4 @@ export const router = createBrowserRouter([
5289
}
5390
]
5491
}
55-
]);
92+
]);

0 commit comments

Comments
 (0)