Skip to content

Commit 2289dfb

Browse files
authored
chore: Navigate to login page when accessing pages that require auth (#468)
1 parent f0b6394 commit 2289dfb

File tree

1 file changed

+49
-5
lines changed

1 file changed

+49
-5
lines changed

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

+49-5
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,60 @@
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+
32+
connector.client.auth.onAuthStateChange(async (event, _session) => {
33+
if (event === 'SIGNED_OUT') {
34+
navigate(LOGIN_ROUTE);
35+
}
36+
});
37+
38+
const loginGuard = () => {
39+
if (!connector.currentSession) {
40+
navigate(LOGIN_ROUTE);
41+
}
42+
}
43+
if (connector.ready) {
44+
loginGuard();
45+
} else {
46+
const l = connector.registerListener({
47+
initialized: () => {
48+
loginGuard();
49+
}
50+
});
51+
return () => l?.();
52+
}
53+
54+
}, []);
55+
return children;
56+
};
57+
1658
/**
1759
* Navigate to this route after authentication
1860
*/
@@ -33,9 +75,11 @@ export const router = createBrowserRouter([
3375
},
3476
{
3577
element: (
36-
<ViewsLayout>
37-
<Outlet />
38-
</ViewsLayout>
78+
<AuthGuard>
79+
<ViewsLayout>
80+
<Outlet />
81+
</ViewsLayout>
82+
</AuthGuard>
3983
),
4084
children: [
4185
{
@@ -52,4 +96,4 @@ export const router = createBrowserRouter([
5296
}
5397
]
5498
}
55-
]);
99+
]);

0 commit comments

Comments
 (0)