import { createRouter, createWebHistory } from 'vue-router' import { useAuthStore } from '@/stores/authStore' const routes = [ { path: '/login', name: 'login', component: () => import('@/views/Login.vue'), meta: { public: true, title: '登录' } }, { // 用 /c/:chatId? 而不是带 query 参数: // 会话 id 是页面身份的一部分,放路径里刷新和分享都更自然 path: '/c/:chatId?', name: 'chat', component: () => import('@/views/Chat.vue'), meta: { title: '对话' } }, { path: '/files', name: 'files', component: () => import('@/views/Files.vue'), meta: { title: '知识库' } }, { // 全局知识库维护:仅管理员可见。 // meta.adminOnly 由路由守卫校验;后端另有 403 兜底, // 前端隐藏只是体验优化,不是安全边界。 path: '/admin/knowledge', name: 'admin-knowledge', component: () => import('@/views/AdminKnowledge.vue'), meta: { title: '全局知识库', adminOnly: true } }, { path: '/', redirect: '/c' }, { path: '/:pathMatch(.*)*', redirect: '/c' } ] const router = createRouter({ history: createWebHistory(), routes }) /** * 全局前置守卫:未登录访问受保护页面时跳转登录页。 * * 这里只做「有没有 token」的粗判断,不校验 token 是否过期 —— * 真正的校验交给后端(返回 401 时由 axios 拦截器统一处理登出)。 * 前端无法可靠判断 JWT 有效性,硬要解析只会引入时钟偏差等问题。 */ router.beforeEach((to) => { const auth = useAuthStore() if (!to.meta.public && !auth.isLoggedIn) { return { name: 'login', query: { redirect: to.fullPath } } } // 已登录用户不应再看到登录页 if (to.name === 'login' && auth.isLoggedIn) { return { name: 'chat' } } // 管理员专属页面:非管理员直接挡回知识库页。 // 注意这只是防止误入,真正的权限校验在后端(会返回 403)。 if (to.meta.adminOnly && !auth.isAdmin) { return { name: 'files' } } return true }) router.afterEach((to) => { document.title = to.meta.title ? `${to.meta.title} · Custom-WebUI` : 'Custom-WebUI' }) export default router