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+
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