import { createBrowserRouter, Navigate, useLocation } from 'react-router-dom'
import { Suspense, lazy } from 'react'
import { useAuthStore, ROLES } from '@/stores/authStore'
// 路由守卫组件
export function AuthGuard({ children }: { children: React.ReactNode }) {
const { isAuthenticated, isLoading } = useAuthStore()
const location = useLocation()
if (isLoading) {
return (
)
}
if (!isAuthenticated) {
return
}
return <>{children}>
}
export function RoleGuard({
children,
roles
}: {
children: React.ReactNode
roles: string[]
}) {
const { hasAnyRole, isAuthenticated, isLoading } = useAuthStore()
const location = useLocation()
if (isLoading) {
return (
)
}
if (!isAuthenticated) {
return
}
if (!hasAnyRole(roles)) {
return
}
return <>{children}>
}
export function AdminGuard({ children }: { children: React.ReactNode }) {
return (
{children}
)
}
export function ModeratorGuard({ children }: { children: React.ReactNode }) {
return (
{children}
)
}
// 公开路由守卫(已登录用户重定向到dashboard)
export function PublicGuard({ children }: { children: React.ReactNode }) {
const { isAuthenticated, isLoading } = useAuthStore()
if (isLoading) {
return (
)
}
if (isAuthenticated) {
return
}
return <>{children}>
}
// 加载指示器组件
function PageLoader() {
return (
)
}
// 懒加载页面组件
const Login = lazy(() => import('@/pages/Login'))
const Dashboard = lazy(() => import('@/pages/Dashboard'))
const Users = lazy(() => import('@/pages/Users'))
const Roles = lazy(() => import('@/pages/Roles'))
const Posts = lazy(() => import('@/pages/Posts'))
const Comments = lazy(() => import('@/pages/Comments'))
const Groups = lazy(() => import('@/pages/Groups'))
const Channels = lazy(() => import('@/pages/Channels'))
const MaterialSubjects = lazy(() => import('@/pages/MaterialSubjects'))
const Materials = lazy(() => import('@/pages/Materials'))
const Forbidden = lazy(() => import('@/pages/Forbidden'))
const NotFound = lazy(() => import('@/pages/NotFound'))
// 布局组件
import MainLayout from '@/components/Layout/MainLayout'
// 创建路由
export const router = createBrowserRouter([
{
path: '/login',
element: (
}>
),
},
{
path: '/',
element: (
),
children: [
{
index: true,
element: ,
},
{
path: 'dashboard',
element: (
}>
),
},
{
path: 'users',
element: (
}>
),
},
{
path: 'roles',
element: (
}>
),
},
{
path: 'posts',
element: (
}>
),
},
{
path: 'comments',
element: (
}>
),
},
{
path: 'groups',
element: (
}>
),
},
{
path: 'channels',
element: (
}>
),
},
{
path: 'materials/subjects',
element: (
}>
),
},
{
path: 'materials',
element: (
}>
),
},
],
},
{
path: '/403',
element: (
}>
),
},
{
path: '*',
element: (
}>
),
},
])
export default router