@kevairy/template 0.1.3 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/package.json +1 -1
  2. package/template/.env +2 -2
  3. package/template/.env.production +6 -0
  4. package/template/src/adapters/auth/index.ts +1 -1
  5. package/template/src/adapters/auth/types.ts +6 -1
  6. package/template/src/api/auth.ts +3 -2
  7. package/template/src/components/core/layouts/art-guide/index.vue +9 -1
  8. package/template/src/components/core/layouts/art-page-content/index.vue +8 -1
  9. package/template/src/config/index.ts +4 -0
  10. package/template/src/directives/core/access.ts +125 -0
  11. package/template/src/directives/core/auth.ts +7 -62
  12. package/template/src/directives/core/roles.ts +5 -83
  13. package/template/src/env.d.ts +1 -0
  14. package/template/src/hooks/core/useAuth.ts +2 -74
  15. package/template/src/hooks/core/useGuide.ts +6 -0
  16. package/template/src/hooks/core/usePermission.ts +41 -0
  17. package/template/src/hooks/index.ts +1 -0
  18. package/template/src/locales/langs/en.json +11 -1
  19. package/template/src/locales/langs/zh.json +11 -1
  20. package/template/src/main.ts +18 -10
  21. package/template/src/router/core/IframeRouteManager.ts +4 -2
  22. package/template/src/router/core/MenuProcessor.ts +5 -40
  23. package/template/src/router/core/RoutePermissionValidator.ts +6 -149
  24. package/template/src/router/core/access.ts +79 -0
  25. package/template/src/router/guards/afterEach.ts +6 -10
  26. package/template/src/router/guards/beforeEach.ts +143 -100
  27. package/template/src/router/guards/error.ts +42 -0
  28. package/template/src/router/index.ts +2 -0
  29. package/template/src/router/modules/examples.ts +4 -3
  30. package/template/src/router/routes/staticRoutes.ts +5 -3
  31. package/template/src/services/auth.ts +32 -10
  32. package/template/src/services/permission.ts +21 -0
  33. package/template/src/store/modules/menu.ts +28 -8
  34. package/template/src/store/modules/user.ts +72 -35
  35. package/template/src/store/modules/worktab.ts +1 -1
  36. package/template/src/types/api/api.d.ts +4 -1
  37. package/template/src/types/config/index.ts +5 -0
  38. package/template/src/types/directive/directive.d.ts +1 -0
  39. package/template/src/types/router/index.ts +6 -0
  40. package/template/src/utils/http/contract.ts +51 -19
  41. package/template/src/utils/http/error.ts +73 -26
  42. package/template/src/utils/http/index.ts +160 -167
  43. package/template/src/utils/http/request-manager.ts +124 -0
  44. package/template/src/utils/http/status.ts +1 -0
  45. package/template/src/utils/permission/index.ts +66 -0
  46. package/template/src/utils/session.ts +24 -0
  47. package/template/src/utils/storage/storage-config.ts +15 -0
  48. package/template/src/utils/storage/storage.ts +5 -3
  49. package/template/src/utils/sys/diagnostics.ts +180 -0
  50. package/template/src/utils/sys/error-handle.ts +56 -126
  51. package/template/src/utils/sys/recovery.ts +31 -0
  52. package/template/src/views/examples/permissions/index.vue +69 -13
  53. package/template/src/views/exception/403/index.vue +33 -0
  54. package/template/src/views/exception/500/index.vue +52 -10
  55. package/template/tests/e2e/permissions.spec.ts +53 -0
  56. package/template/tests/e2e/session-recovery.spec.ts +49 -0
  57. package/template/tests/unit/diagnostics/diagnostics.spec.ts +132 -0
  58. package/template/tests/unit/diagnostics/router.spec.ts +84 -0
  59. package/template/tests/unit/http/auth-lifecycle.spec.ts +203 -0
  60. package/template/tests/unit/http/contract.spec.ts +46 -0
  61. package/template/tests/unit/http/request.spec.ts +487 -0
  62. package/template/tests/unit/permissions/guard.spec.ts +261 -0
  63. package/template/tests/unit/permissions/guide.spec.ts +30 -0
  64. package/template/tests/unit/permissions/rules.spec.ts +106 -0
  65. package/template/tests/unit/permissions/state-and-directives.spec.ts +176 -0
  66. package/template/tests/unit/router/examples.spec.ts +5 -1
  67. package/template/vite.config.ts +5 -2
@@ -36,7 +36,7 @@
36
36
  * @author Art Design Pro Team
37
37
  */
38
38
  import type { Router, RouteLocationNormalized, NavigationGuardNext } from 'vue-router'
39
- import { nextTick } from 'vue'
39
+ import { nextTick, watch } from 'vue'
40
40
  import NProgress from 'nprogress'
41
41
  import { useSettingStore } from '@/store/modules/setting'
42
42
  import { useUserStore } from '@/store/modules/user'
@@ -50,8 +50,15 @@ import { useCommon } from '@/hooks/core/useCommon'
50
50
  import { useWorktabStore } from '@/store/modules/worktab'
51
51
  import { fetchGetUserInfo } from '@/api/auth'
52
52
  import { ApiStatus } from '@/utils/http/status'
53
- import { isHttpError } from '@/utils/http/error'
54
- import { RouteRegistry, MenuProcessor, IframeRouteManager, RoutePermissionValidator } from '../core'
53
+ import { isHttpError, isRequestCanceled } from '@/utils/http/error'
54
+ import { getSessionVersion } from '@/utils/http/request-manager'
55
+ import { reportDiagnostic } from '@/utils/sys/diagnostics'
56
+ import AppConfig from '@/config'
57
+ import { canAccessMeta } from '@/utils/permission'
58
+ import type { AccessMeta } from '@/utils/permission'
59
+ import type { AppRouteRecord } from '@/types/router'
60
+ import { canAccessRoute, resolveRouteChain } from '../core/access'
61
+ import { RouteRegistry, MenuProcessor, IframeRouteManager } from '../core'
55
62
 
56
63
  // 路由注册器实例
57
64
  let routeRegistry: RouteRegistry | null = null
@@ -63,11 +70,12 @@ const menuProcessor = new MenuProcessor()
63
70
  let pendingLoading = false
64
71
 
65
72
  // 路由初始化失败标记,防止死循环
66
- // 一旦设置为 true,只有刷新页面或重新登录才能重置
73
+ // 由恢复页重试、刷新授权或会话切换重置
67
74
  let routeInitFailed = false
68
75
 
69
76
  // 路由初始化进行中标记,防止并发请求
70
77
  let routeInitInProgress = false
78
+ let routeInitVersion = 0
71
79
 
72
80
  /**
73
81
  * 获取 pendingLoading 状态
@@ -76,6 +84,10 @@ export function getPendingLoading(): boolean {
76
84
  return pendingLoading
77
85
  }
78
86
 
87
+ export function getRouteInitInProgress(): boolean {
88
+ return routeInitInProgress
89
+ }
90
+
79
91
  /**
80
92
  * 重置 pendingLoading 状态
81
93
  */
@@ -94,6 +106,7 @@ export function getRouteInitFailed(): boolean {
94
106
  * 重置路由初始化状态(用于重新登录场景)
95
107
  */
96
108
  export function resetRouteInitState(): void {
109
+ routeInitVersion++
97
110
  routeInitFailed = false
98
111
  routeInitInProgress = false
99
112
  }
@@ -101,11 +114,25 @@ export function resetRouteInitState(): void {
101
114
  /**
102
115
  * 设置路由全局前置守卫
103
116
  */
104
- export function setupBeforeEachGuard(router: Router): void {
117
+ export function setupBeforeEachGuard(router: Router): () => void {
105
118
  // 初始化路由注册器
106
119
  routeRegistry = new RouteRegistry(router)
120
+ const user = useUserStore()
121
+ // 授权变化时重新注册菜单树,并立即离开已失去权限的页面。
122
+ const stopWatching = watch(
123
+ () => [user.permissionsReady, user.permissions, user.roles],
124
+ () => {
125
+ if (routeInitInProgress || !routeRegistry?.isRegistered()) return
126
+ registerAccessibleRoutes()
127
+ const current = router.currentRoute.value
128
+ if (!isStaticRoute(current.path) && !hasRouteAccess(current, router)) {
129
+ void router.replace({ name: 'Exception403' })
130
+ }
131
+ },
132
+ { deep: true }
133
+ )
107
134
 
108
- router.beforeEach(
135
+ const removeGuard = router.beforeEach(
109
136
  async (
110
137
  to: RouteLocationNormalized,
111
138
  from: RouteLocationNormalized,
@@ -114,20 +141,26 @@ export function setupBeforeEachGuard(router: Router): void {
114
141
  try {
115
142
  await handleRouteGuard(to, from, next, router)
116
143
  } catch (error) {
117
- console.error('[RouteGuard] 路由守卫处理失败:', error)
144
+ reportDiagnostic('router', error)
118
145
  closeLoading()
119
146
  next({ name: 'Exception500' })
120
147
  }
121
148
  }
122
149
  )
150
+ return () => {
151
+ stopWatching()
152
+ removeGuard()
153
+ }
123
154
  }
124
155
 
125
156
  /**
126
157
  * 关闭 loading 效果
127
158
  */
128
- function closeLoading(): void {
159
+ export function closeLoading(): void {
129
160
  if (pendingLoading) {
161
+ const version = routeInitVersion
130
162
  nextTick(() => {
163
+ if (version !== routeInitVersion) return
131
164
  loadingService.hideLoading()
132
165
  pendingLoading = false
133
166
  })
@@ -145,6 +178,10 @@ async function handleRouteGuard(
145
178
  ): Promise<void> {
146
179
  const settingStore = useSettingStore()
147
180
  const userStore = useUserStore()
181
+ if (userStore.isSigningOut) {
182
+ next(false)
183
+ return
184
+ }
148
185
 
149
186
  // 启动进度条
150
187
  if (settingStore.showNprogress) {
@@ -156,20 +193,24 @@ async function handleRouteGuard(
156
193
  return
157
194
  }
158
195
 
159
- // 2. 检查路由初始化是否已失败(防止死循环)
196
+ // 匿名系统页不依赖权限初始化,保证错误页和登录页始终可以恢复。
197
+ if (
198
+ !userStore.isLogin ||
199
+ (isStaticRoute(to.path) &&
200
+ (to.name !== 'Exception403' || userStore.permissionsReady || routeInitFailed))
201
+ ) {
202
+ setPageTitle(to)
203
+ next()
204
+ return
205
+ }
206
+
160
207
  if (routeInitFailed) {
161
- // 已经失败过,直接放行到错误页面,不再重试
162
- if (to.matched.length > 0) {
163
- next()
164
- } else {
165
- // 未匹配到路由,跳转到 500 页面
166
- next({ name: 'Exception500', replace: true })
167
- }
208
+ next({ name: 'Exception500', replace: true })
168
209
  return
169
210
  }
170
211
 
171
212
  // 3. 处理动态路由注册
172
- if (!routeRegistry?.isRegistered() && userStore.isLogin) {
213
+ if ((!routeRegistry?.isRegistered() || !userStore.permissionsReady) && userStore.isLogin) {
173
214
  // 防止并发请求(快速连续导航场景)
174
215
  if (routeInitInProgress) {
175
216
  // 正在初始化中,等待完成后重新导航
@@ -186,15 +227,24 @@ async function handleRouteGuard(
186
227
  }
187
228
 
188
229
  // 5. 处理已匹配的路由
189
- if (to.matched.length > 0) {
230
+ if (to.matched.length > 0 && to.name !== 'Exception404') {
231
+ if (!hasRouteAccess(to, router)) {
232
+ next({ name: 'Exception403', replace: true })
233
+ return
234
+ }
190
235
  setWorktab(to)
191
236
  setPageTitle(to)
192
237
  next()
193
238
  return
194
239
  }
195
240
 
196
- // 6. 未匹配到路由,跳转到 404
197
- next({ name: 'Exception404' })
241
+ // 被授权过滤掉的已声明页面是 403,完全未知的地址是 404。
242
+ const declared = resolveRouteChain(to.path, useMenuStore().routeList).length > 0
243
+ if (declared) next({ name: 'Exception403', replace: true })
244
+ else {
245
+ setPageTitle(to)
246
+ next()
247
+ }
198
248
  }
199
249
 
200
250
  /**
@@ -230,31 +280,43 @@ function handleLoginStatus(
230
280
  /**
231
281
  * 检查路由是否为静态路由
232
282
  */
233
- function isStaticRoute(path: string): boolean {
234
- const checkRoute = (routes: any[], targetPath: string): boolean => {
235
- return routes.some((route) => {
236
- // 404 catch-all 路由不应视为可匿名访问的静态页,
237
- // 否则未登录时手动输入任意地址会直接落到 404,无法跳转登录页。
238
- if (route.name === 'Exception404') {
239
- return false
240
- }
241
-
242
- // 处理动态路由参数匹配
243
- const routePath = route.path
244
- const pattern = routePath.replace(/:[^/]+/g, '[^/]+').replace(/\*/g, '.*')
245
- const regex = new RegExp(`^${pattern}$`)
283
+ function isStaticRoute(path: string, includeProtected = false): boolean {
284
+ const chain = resolveRouteChain(path, staticRoutes as unknown as AppRouteRecord[])
285
+ if (!chain.length || chain.at(-1)?.name === 'Exception404') return false
286
+ return (
287
+ includeProtected ||
288
+ chain.every(
289
+ ({ meta }) => !meta.requiresAuth && meta.roles === undefined && meta.permissions === undefined
290
+ )
291
+ )
292
+ }
246
293
 
247
- if (regex.test(targetPath)) {
248
- return true
249
- }
250
- if (route.children && route.children.length > 0) {
251
- return checkRoute(route.children, targetPath)
252
- }
253
- return false
254
- })
294
+ function currentAccess() {
295
+ const user = useUserStore()
296
+ return {
297
+ ready: user.permissionsReady,
298
+ permissions: user.permissions,
299
+ roles: user.roles,
300
+ wildcard: AppConfig.accessControl.wildcardPermission
255
301
  }
302
+ }
256
303
 
257
- return checkRoute(staticRoutes, path)
304
+ function hasRouteAccess(to: RouteLocationNormalized, router: Router): boolean {
305
+ const access = currentAccess()
306
+ const matched = router.resolve(to.fullPath).matched
307
+ if (!matched.length || matched.at(-1)?.name === 'Exception404') return false
308
+ if (!matched.every(({ meta }) => canAccessMeta(meta as AccessMeta, access))) return false
309
+ return isStaticRoute(to.path, true) || canAccessRoute(to.path, useMenuStore().routeList, access)
310
+ }
311
+
312
+ function registerAccessibleRoutes(): void {
313
+ const menuStore = useMenuStore()
314
+ routeRegistry?.unregister()
315
+ menuStore.removeAllDynamicRoutes()
316
+ IframeRouteManager.getInstance().clear()
317
+ routeRegistry?.register(menuStore.menuList)
318
+ menuStore.addRemoveRouteFns(routeRegistry?.getRemoveRouteFns() || [])
319
+ IframeRouteManager.getInstance().save()
258
320
  }
259
321
 
260
322
  /**
@@ -265,6 +327,9 @@ async function handleDynamicRoutes(
265
327
  next: NavigationGuardNext,
266
328
  router: Router
267
329
  ): Promise<void> {
330
+ const session = getSessionVersion()
331
+ const task = ++routeInitVersion
332
+ const isCurrent = () => session === getSessionVersion() && task === routeInitVersion
268
333
  // 标记初始化进行中
269
334
  routeInitInProgress = true
270
335
 
@@ -274,26 +339,31 @@ async function handleDynamicRoutes(
274
339
 
275
340
  try {
276
341
  // 1. 获取用户信息
277
- await fetchUserInfo()
342
+ if (!useUserStore().permissionsReady) {
343
+ const data = await fetchGetUserInfo()
344
+ if (!isCurrent()) {
345
+ next(false)
346
+ return
347
+ }
348
+ useUserStore().setUserInfo(data)
349
+ useUserStore().checkAndClearWorktabs()
350
+ }
278
351
 
279
352
  // 2. 获取菜单数据
280
353
  const menuList = await menuProcessor.getMenuList()
354
+ if (!isCurrent()) {
355
+ next(false)
356
+ return
357
+ }
281
358
 
282
359
  // 3. 验证菜单数据
283
360
  if (!menuProcessor.validateMenuList(menuList)) {
284
361
  throw new Error('获取菜单列表失败,请重新登录')
285
362
  }
286
363
 
287
- // 4. 注册动态路由
288
- routeRegistry?.register(menuList)
289
-
290
- // 5. 保存菜单数据到 store
291
364
  const menuStore = useMenuStore()
292
365
  menuStore.setMenuList(menuList)
293
- menuStore.addRemoveRouteFns(routeRegistry?.getRemoveRouteFns() || [])
294
-
295
- // 6. 保存 iframe 路由
296
- IframeRouteManager.getInstance().save()
366
+ registerAccessibleRoutes()
297
367
 
298
368
  // 7. 验证工作标签页
299
369
  useWorktabStore().validateWorktabs(router)
@@ -310,53 +380,37 @@ async function handleDynamicRoutes(
310
380
  return
311
381
  }
312
382
 
313
- // 8. 验证目标路径权限
314
- const { homePath } = useCommon()
315
- const { path: validatedPath, hasPermission } = RoutePermissionValidator.validatePath(
316
- to.path,
317
- menuList,
318
- homePath.value || '/'
319
- )
320
-
321
- // 初始化成功,重置进行中标记
322
383
  routeInitInProgress = false
323
-
324
- // 9. 重新导航到目标路由
325
- if (!hasPermission) {
326
- // 无权限访问,跳转到首页
327
- closeLoading()
328
-
329
- // 输出警告信息
330
- console.warn(`[RouteGuard] 用户无权限访问路径: ${to.path},已跳转到首页`)
331
-
332
- // 直接跳转到首页
333
- next({
334
- path: validatedPath,
335
- replace: true
336
- })
337
- } else {
338
- // 有权限,正常导航
339
- next({
340
- path: to.path,
341
- query: to.query,
342
- hash: to.hash,
343
- replace: true
344
- })
384
+ if (to.path === '/') {
385
+ next({ path: menuStore.homePath, replace: true })
386
+ return
387
+ }
388
+ if (menuStore.menuList.length === 0 || !hasRouteAccess(to, router)) {
389
+ const declared = resolveRouteChain(to.path, menuStore.routeList).length > 0
390
+ if (menuStore.menuList.length === 0 || declared) next({ name: 'Exception403', replace: true })
391
+ else next({ path: to.path, query: to.query, hash: to.hash, replace: true })
392
+ return
345
393
  }
394
+ next({ path: to.path, query: to.query, hash: to.hash, replace: true })
346
395
  } catch (error) {
347
- console.error('[RouteGuard] 动态路由注册失败:', error)
396
+ if (!isCurrent()) {
397
+ next(false)
398
+ return
399
+ }
348
400
 
349
401
  // 关闭 loading
350
402
  closeLoading()
351
403
 
352
404
  // 401 错误:axios 拦截器已处理退出登录,取消当前导航
353
- if (isUnauthorizedError(error)) {
405
+ if (isUnauthorizedError(error) || isRequestCanceled(error)) {
354
406
  // 重置状态,允许重新登录后再次初始化
355
407
  routeInitInProgress = false
356
408
  next(false)
357
409
  return
358
410
  }
359
411
 
412
+ reportDiagnostic('router', error)
413
+
360
414
  if (isForbiddenError(error)) {
361
415
  routeInitFailed = true
362
416
  routeInitInProgress = false
@@ -368,32 +422,21 @@ async function handleDynamicRoutes(
368
422
  routeInitFailed = true
369
423
  routeInitInProgress = false
370
424
 
371
- // 输出详细错误信息,便于排查
372
- if (isHttpError(error)) {
373
- console.error(`[RouteGuard] 错误码: ${error.code}, 消息: ${error.message}`)
374
- }
375
-
376
425
  // 跳转到 500 页面,使用 replace 避免产生历史记录
377
426
  next({ name: 'Exception500', replace: true })
378
427
  }
379
428
  }
380
429
 
381
- /**
382
- * 获取用户信息
383
- */
384
- async function fetchUserInfo(): Promise<void> {
385
- const userStore = useUserStore()
386
- const data = await fetchGetUserInfo()
387
- userStore.setUserInfo(data)
388
- // 检查并清理工作台标签页(如果是不同用户登录)
389
- userStore.checkAndClearWorktabs()
390
- }
391
-
392
430
  /**
393
431
  * 重置路由相关状态
394
432
  */
395
433
  export function resetRouterState(delay: number): void {
434
+ const session = getSessionVersion()
435
+ const version = routeInitVersion
396
436
  const reset = () => {
437
+ if (delay > 0 && (session !== getSessionVersion() || version !== routeInitVersion)) return
438
+ if (pendingLoading) loadingService.hideLoading()
439
+ pendingLoading = false
397
440
  routeRegistry?.unregister()
398
441
  IframeRouteManager.getInstance().clear()
399
442
 
@@ -0,0 +1,42 @@
1
+ import type { Router } from 'vue-router'
2
+ import NProgress from 'nprogress'
3
+ import { closeLoading } from './beforeEach'
4
+ import { reportDiagnostic, setDiagnosticRouteProvider } from '@/utils/sys/diagnostics'
5
+ import { isChunkLoadError, markResourceFailure } from '@/utils/sys/recovery'
6
+ import { isRequestCanceled } from '@/utils/http/error'
7
+ import { getSessionVersion } from '@/utils/http/request-manager'
8
+
9
+ /** 路由和 Vite 资源错误仅记录一次导航失败,不把正常的取消转换成 500。 */
10
+ export function setupRouterErrorHandler(router: Router): () => void {
11
+ setDiagnosticRouteProvider(() => router.currentRoute.value.fullPath)
12
+ let navigation = 0
13
+ const tasks = new WeakMap<object, { session: number; navigation: number }>()
14
+ const removeGuard = router.beforeEach((to) => {
15
+ tasks.set(to, { session: getSessionVersion(), navigation: ++navigation })
16
+ })
17
+ const remove = router.onError((error, to) => {
18
+ if (isRequestCanceled(error)) return
19
+ const task = tasks.get(to)
20
+ if (task && (task.session !== getSessionVersion() || task.navigation !== navigation)) return
21
+ reportDiagnostic('router', error, { url: to.fullPath })
22
+ NProgress.done()
23
+ closeLoading()
24
+ if (isChunkLoadError(error)) markResourceFailure(to.fullPath)
25
+ if (to.name !== 'Exception500') {
26
+ void router
27
+ .replace({ name: 'Exception500' })
28
+ .catch((failure) => reportDiagnostic('router', failure))
29
+ }
30
+ })
31
+ const preload = (event: Event) => {
32
+ const error = (event as Event & { payload?: unknown }).payload
33
+ reportDiagnostic('resource', error ?? 'Vite preload failed')
34
+ // 不阻止默认异常,让 router.onError 完成导航恢复。
35
+ }
36
+ window.addEventListener('vite:preloadError', preload)
37
+ return () => {
38
+ remove()
39
+ removeGuard()
40
+ window.removeEventListener('vite:preloadError', preload)
41
+ }
42
+ }
@@ -5,6 +5,7 @@ import { configureNProgress } from '@/utils/router'
5
5
  import { setupBeforeEachGuard } from './guards/beforeEach'
6
6
  import { setupAfterEachGuard } from './guards/afterEach'
7
7
  import AppConfig from '@/config'
8
+ import { setupRouterErrorHandler } from './guards/error'
8
9
 
9
10
  // 创建路由实例
10
11
  export const router = createRouter({
@@ -17,6 +18,7 @@ export function initRouter(app: App<Element>): void {
17
18
  configureNProgress() // 顶部进度条
18
19
  setupBeforeEachGuard(router) // 路由前置守卫
19
20
  setupAfterEachGuard(router) // 路由后置守卫
21
+ setupRouterErrorHandler(router)
20
22
  app.use(router)
21
23
  }
22
24
 
@@ -68,9 +68,9 @@ export const examplesRoutes: AppRouteRecord = {
68
68
  title: 'menus.examples.permissions',
69
69
  icon: 'ri:shield-keyhole-line',
70
70
  authList: [
71
- { title: '新增', authMark: 'create' },
72
- { title: '编辑', authMark: 'edit' },
73
- { title: '导出', authMark: 'export' }
71
+ { title: '新增', authMark: 'example:resource:create' },
72
+ { title: '编辑', authMark: 'example:resource:edit' },
73
+ { title: '导出', authMark: 'example:resource:export' }
74
74
  ],
75
75
  keepAlive: true
76
76
  }
@@ -98,6 +98,7 @@ export const examplesRoutes: AppRouteRecord = {
98
98
  component: '/examples/navigation/detail',
99
99
  meta: {
100
100
  title: 'menus.examples.navigation.detail',
101
+ permissions: ['example:navigation:read'],
101
102
  isHide: true,
102
103
  activePath: '/examples/navigation/state'
103
104
  }
@@ -1,4 +1,5 @@
1
1
  import { AppRouteRecordRaw } from '@/utils/router'
2
+ import Exception500 from '@/views/exception/500/index.vue'
2
3
 
3
4
  /**
4
5
  * 静态路由配置(不需要权限就能访问的路由)
@@ -39,21 +40,22 @@ export const staticRoutes: AppRouteRecordRaw[] = [
39
40
  {
40
41
  path: '/500',
41
42
  name: 'Exception500',
42
- component: () => import('@views/exception/500/index.vue'),
43
+ // 恢复页跟随入口打包,业务页面 chunk 失效时仍能展示刷新入口。
44
+ component: Exception500,
43
45
  meta: { title: '500', isHideTab: true }
44
46
  },
45
47
  {
46
48
  path: '/outside',
47
49
  component: () => import('@views/index/index.vue'),
48
50
  name: 'Outside',
49
- meta: { title: 'menus.outside.title' },
51
+ meta: { title: 'menus.outside.title', requiresAuth: true },
50
52
  children: [
51
53
  // iframe 内嵌页面
52
54
  {
53
55
  path: '/outside/iframe/:path',
54
56
  name: 'Iframe',
55
57
  component: () => import('@/views/outside/Iframe.vue'),
56
- meta: { title: 'iframe' }
58
+ meta: { title: 'iframe', requiresAuth: true }
57
59
  }
58
60
  ]
59
61
  }
@@ -1,15 +1,37 @@
1
1
  import { fetchLogout } from '@/api/auth'
2
2
  import { useUserStore } from '@/store/modules/user'
3
+ import { getSessionVersion, SIGN_OUT_REQUEST_SCOPE } from '@/utils/http/request-manager'
4
+ import { isRequestCanceled } from '@/utils/http/error'
5
+ import { reportDiagnostic } from '@/utils/sys/diagnostics'
3
6
 
4
- /** 执行退出流程,并始终清理本地认证状态。 */
5
- export async function signOut(): Promise<void> {
6
- const userStore = useUserStore()
7
+ let pending: { session: number; task: Promise<void> } | undefined
7
8
 
8
- try {
9
- await fetchLogout()
10
- } catch (error) {
11
- console.warn('[Auth] 退出处理失败,已继续清理本地会话', error)
12
- } finally {
13
- userStore.clearAuthState()
14
- }
9
+ /** 退出当前会话,并保护期间建立的新会话。 */
10
+ export function signOut(): Promise<void> {
11
+ const userStore = useUserStore()
12
+ if (pending?.session === getSessionVersion()) return pending.task
13
+ if (!userStore.isLogin && !userStore.accessToken) return Promise.resolve()
14
+ userStore.beginSignOut()
15
+ const session = getSessionVersion()
16
+ const task = (async () => {
17
+ let timer: ReturnType<typeof setTimeout> | undefined
18
+ try {
19
+ // 保留旧凭据直到远端调用完成;自定义适配器也最多等待 10 秒。
20
+ await Promise.race([
21
+ fetchLogout({ requestScope: SIGN_OUT_REQUEST_SCOPE }),
22
+ new Promise<never>((_, reject) => {
23
+ timer = setTimeout(() => reject(new Error('Remote sign-out timed out')), 10000)
24
+ })
25
+ ])
26
+ } catch (error) {
27
+ if (session === getSessionVersion() && !isRequestCanceled(error))
28
+ reportDiagnostic('session', error)
29
+ } finally {
30
+ clearTimeout(timer)
31
+ if (session === getSessionVersion()) userStore.clearAuthState()
32
+ if (pending?.session === session) pending = undefined
33
+ }
34
+ })()
35
+ pending = { session, task }
36
+ return task
15
37
  }
@@ -0,0 +1,21 @@
1
+ import { fetchGetUserInfo } from '@/api/auth'
2
+ import { router } from '@/router'
3
+ import { resetRouterState } from '@/router/guards/beforeEach'
4
+ import { useUserStore } from '@/store/modules/user'
5
+ import { getSessionVersion } from '@/utils/http/request-manager'
6
+
7
+ let refreshVersion = 0
8
+
9
+ /** 显式刷新用户授权及后端菜单;失败交给调用方展示,401 仍由认证层处理。 */
10
+ export async function refreshAccess(): Promise<void> {
11
+ const session = getSessionVersion()
12
+ const task = ++refreshVersion
13
+ const user = useUserStore()
14
+ if (!user.isLogin || user.isSigningOut) return
15
+ const info = await fetchGetUserInfo()
16
+ if (session !== getSessionVersion() || task !== refreshVersion || user.isSigningOut) return
17
+ user.setUserInfo(info)
18
+ user.checkAndClearWorktabs()
19
+ resetRouterState(0)
20
+ await router.replace('/')
21
+ }
@@ -29,9 +29,11 @@
29
29
  * @author Art Design Pro Team
30
30
  */
31
31
  import { defineStore } from 'pinia'
32
- import { ref } from 'vue'
32
+ import { ref, shallowRef, computed } from 'vue'
33
33
  import { AppRouteRecord } from '@/types/router'
34
- import { getFirstMenuPath } from '@/utils'
34
+ import { useUserStore } from './user'
35
+ import AppConfig from '@/config'
36
+ import { filterAccessibleRoutes, firstAccessiblePath, canAccessRoute } from '@/router/core/access'
35
37
  import { HOME_PAGE_PATH } from '@/router'
36
38
 
37
39
  /**
@@ -40,9 +42,25 @@ import { HOME_PAGE_PATH } from '@/router'
40
42
  */
41
43
  export const useMenuStore = defineStore('menuStore', () => {
42
44
  /** 首页路径 */
43
- const homePath = ref(HOME_PAGE_PATH)
44
- /** 菜单列表 */
45
- const menuList = ref<AppRouteRecord[]>([])
45
+ const preferredHomePath = ref(HOME_PAGE_PATH)
46
+ // 只保存适配器返回的路由源,授权树随当前用户权限重新计算。
47
+ const routeList = shallowRef<AppRouteRecord[]>([])
48
+ const access = computed(() => {
49
+ const user = useUserStore()
50
+ return {
51
+ ready: user.permissionsReady,
52
+ permissions: user.permissions,
53
+ roles: user.roles,
54
+ wildcard: AppConfig.accessControl.wildcardPermission
55
+ }
56
+ })
57
+ const menuList = computed(() => filterAccessibleRoutes(routeList.value, access.value))
58
+ const homePath = computed(() => {
59
+ const preferred = preferredHomePath.value
60
+ if (preferred && preferred !== '/' && canAccessRoute(preferred, menuList.value, access.value))
61
+ return preferred
62
+ return firstAccessiblePath(menuList.value) || '/403'
63
+ })
46
64
  /** 菜单宽度 */
47
65
  const menuWidth = ref('')
48
66
  /** 存储路由移除函数的数组 */
@@ -53,8 +71,8 @@ export const useMenuStore = defineStore('menuStore', () => {
53
71
  * @param list 菜单路由记录数组
54
72
  */
55
73
  const setMenuList = (list: AppRouteRecord[]) => {
56
- menuList.value = list
57
- setHomePath(HOME_PAGE_PATH || getFirstMenuPath(list))
74
+ routeList.value = list
75
+ preferredHomePath.value = HOME_PAGE_PATH
58
76
  }
59
77
 
60
78
  /**
@@ -68,7 +86,7 @@ export const useMenuStore = defineStore('menuStore', () => {
68
86
  * @param path 主页路径
69
87
  */
70
88
  const setHomePath = (path: string) => {
71
- homePath.value = path
89
+ preferredHomePath.value = path
72
90
  }
73
91
 
74
92
  /**
@@ -96,7 +114,9 @@ export const useMenuStore = defineStore('menuStore', () => {
96
114
  }
97
115
 
98
116
  return {
117
+ homePath,
99
118
  menuList,
119
+ routeList,
100
120
  menuWidth,
101
121
  removeRouteFns,
102
122
  setMenuList,