1- import { Outlet , createBrowserRouter } from 'react-router-dom' ;
1+ import { Outlet , createBrowserRouter , useNavigate } from 'react-router-dom' ;
22import LoginPage from '@/app/auth/login/page' ;
33import RegisterPage from '@/app/auth/register/page' ;
44import EntryPage from '@/app/page' ;
55import TodoEditPage from '@/app/views/todo-lists/edit/page' ;
66import TodoListsPage from '@/app/views/todo-lists/page' ;
77import ViewsLayout from '@/app/views/layout' ;
88import SQLConsolePage from '@/app/views/sql-console/page' ;
9+ import { useSupabase } from '@/components/providers/SystemProvider' ;
10+ import React from 'react' ;
911
1012export const TODO_LISTS_ROUTE = '/views/todo-lists' ;
1113export const TODO_EDIT_ROUTE = '/views/todo-lists/:id' ;
1214export const LOGIN_ROUTE = '/auth/login' ;
1315export const REGISTER_ROUTE = '/auth/register' ;
1416export 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