Skip to content
Merged
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 50 additions & 5 deletions demos/react-supabase-todolist/src/app/router.tsx
Original file line number Diff line number Diff line change
@@ -1,18 +1,61 @@
import { Outlet, createBrowserRouter } from 'react-router-dom';
import { Outlet, createBrowserRouter, useNavigate } from 'react-router-dom';
import LoginPage from '@/app/auth/login/page';
import RegisterPage from '@/app/auth/register/page';
import EntryPage from '@/app/page';
import TodoEditPage from '@/app/views/todo-lists/edit/page';
import TodoListsPage from '@/app/views/todo-lists/page';
import ViewsLayout from '@/app/views/layout';
import SQLConsolePage from '@/app/views/sql-console/page';
import { useSupabase } from '@/components/providers/SystemProvider';
import React from 'react';

export const TODO_LISTS_ROUTE = '/views/todo-lists';
export const TODO_EDIT_ROUTE = '/views/todo-lists/:id';
export const LOGIN_ROUTE = '/auth/login';
export const REGISTER_ROUTE = '/auth/register';
export const SQL_CONSOLE_ROUTE = '/sql-console';

interface AuthGuardProps {
children: JSX.Element;
}

const AuthGuard = ({ children }: AuthGuardProps) => {
const connector = useSupabase()

const navigate = useNavigate();
React.useEffect(() => {
if (!connector) {
console.error(`No Supabase connector has been created yet.`);
return;
}

connector.client.auth.onAuthStateChange(async (event, _session) => {
if (event === 'SIGNED_OUT') {
console.log("here");
navigate(LOGIN_ROUTE);
}
});

const loginGuard = () => {
if (!connector.currentSession) {
navigate(LOGIN_ROUTE);
}
}
if (connector.ready) {
loginGuard();
} else {
const l = connector.registerListener({
initialized: () => {
loginGuard();
}
});
return () => l?.();
}

}, []);
return children;
};

/**
* Navigate to this route after authentication
*/
Expand All @@ -33,9 +76,11 @@ export const router = createBrowserRouter([
},
{
element: (
<ViewsLayout>
<Outlet />
</ViewsLayout>
<AuthGuard>
<ViewsLayout>
<Outlet />
</ViewsLayout>
</AuthGuard>
),
children: [
{
Expand All @@ -52,4 +97,4 @@ export const router = createBrowserRouter([
}
]
}
]);
]);
Loading