Refactor navigation and authentication flow

- Move navigation setup to AppRouter
- Prevent protected route logic to handle login 401
This commit is contained in:
yangdx
2025-03-19 19:08:09 +08:00
parent 0339273fe9
commit 99814b57d9
5 changed files with 75 additions and 46 deletions

View File

@@ -1,4 +1,4 @@
import { HashRouter as Router, Routes, Route, Navigate } from 'react-router-dom'
import { HashRouter as Router, Routes, Route, useNavigate } from 'react-router-dom'
import { useEffect, useState } from 'react'
import { useAuthStore } from '@/stores/state'
import { navigationService } from '@/services/navigation'
@@ -16,6 +16,12 @@ interface ProtectedRouteProps {
const ProtectedRoute = ({ children }: ProtectedRouteProps) => {
const { isAuthenticated } = useAuthStore()
const [isChecking, setIsChecking] = useState(true)
const navigate = useNavigate()
// Set navigate function for navigation service
useEffect(() => {
navigationService.setNavigate(navigate)
}, [navigate])
useEffect(() => {
let isMounted = true; // Flag to prevent state updates after unmount
@@ -71,29 +77,33 @@ const ProtectedRoute = ({ children }: ProtectedRouteProps) => {
// Get current path and check if it's a direct access
const currentPath = window.location.hash.slice(1); // Remove the '#' from hash
const isLoginPage = currentPath === '/login';
const isDirectAccess = !document.referrer;
// Handle direct access to root path
if (isDirectAccess && currentPath === '/') {
navigationService.resetAllApplicationState();
}
// Skip redirect if already on login page
if (isLoginPage) {
return null;
}
// Use React Router's Navigate for redirection
console.log('Not authenticated, redirecting to login');
return <Navigate to="/login" replace />;
// For non-login pages, handle state reset and navigation
if (!isLoginPage) {
// Use navigation service for redirection
console.log('Not authenticated, redirecting to login');
navigationService.navigateToLogin();
return null;
}
}
return <>{children}</>
}
const AppRouter = () => {
const AppContent = () => {
const [initializing, setInitializing] = useState(true)
const { isAuthenticated } = useAuthStore()
const navigate = useNavigate()
// Set navigate function for navigation service
useEffect(() => {
navigationService.setNavigate(navigate)
}, [navigate])
// Check token validity and auth configuration on app initialization
useEffect(() => {
@@ -152,21 +162,27 @@ const AppRouter = () => {
return null
}
return (
<Routes>
<Route path="/login" element={<LoginPage />} />
<Route
path="/*"
element={
<ProtectedRoute>
<App />
</ProtectedRoute>
}
/>
</Routes>
)
}
const AppRouter = () => {
return (
<ThemeProvider>
<Router>
<Routes>
<Route path="/login" element={<LoginPage />} />
<Route
path="/*"
element={
<ProtectedRoute>
<App />
</ProtectedRoute>
}
/>
</Routes>
<Toaster position="top-center" />
<AppContent />
<Toaster position="bottom-center" />
</Router>
</ThemeProvider>
)