kongdeqiang
2026-10-09 f55d84f8479f35f780c535d2d4f4836727363255
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
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