路由守卫改为按 requiresAuth 自动拦截 #3391

原 protectedRoutes 数组只覆盖 8 项,9 个显式标 requiresAuth 的路由只有 2 个被守卫。改成 to.matched.some(r => r.meta.requiresAuth) 自动收口,anon 白名单按 name 反向匹配避免误伤登录/注册/找回密码页。注意 dict/management 等路由当前未标 requiresAuth,按 DoD 不动路由表,本 PR 不覆盖它们;完整修复需后续给这些路由补标记。
This commit is contained in:
hrz 2026-10-07 10:22:10 +08:00
parent 7a260ee143
commit c08d9af5e3

View file

@ -228,20 +228,19 @@ VueRouter.prototype.push = function push(location) {
}) })
} }
// 需要登录才能访问的路由 // 任何路由段上 meta.requiresAuth === true 都视为需要登录
const protectedRoutes = ['home', 'RoleConfig', 'DeviceManagement', 'UserManagement', 'ModelConfig', 'KnowledgeBaseManagement', 'KnowledgeFileUpload', 'AddressBookManagement'] // 匿名白名单按 name 匹配,避免被误标时也拦住 anon 路由
const anonRouteNames = new Set(['login', 'Register', 'RetrievePassword'])
// 路由守卫
router.beforeEach((to, from, next) => { router.beforeEach((to, from, next) => {
// 检查是否是需要保护的路由 if (anonRouteNames.has(to.name)) {
if (protectedRoutes.includes(to.name)) { next()
// 从localStorage获取token return
const token = localStorage.getItem('token') }
if (!token) { const requiresAuth = to.matched.some(r => r.meta && r.meta.requiresAuth === true)
// 未登录,跳转到登录页 if (requiresAuth && !localStorage.getItem('token')) {
next({ name: 'login', query: { redirect: to.fullPath } }) next({ name: 'login', query: { redirect: to.fullPath } })
return return
}
} }
next() next()
}) })