@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
@@ -0,0 +1,180 @@
1
+ export type DiagnosticKind =
2
+ | 'vue'
3
+ | 'script'
4
+ | 'promise'
5
+ | 'resource'
6
+ | 'http'
7
+ | 'router'
8
+ | 'bootstrap'
9
+ | 'session'
10
+
11
+ export interface DiagnosticContext {
12
+ url?: string
13
+ source?: string
14
+ line?: number
15
+ column?: number
16
+ component?: string
17
+ info?: string
18
+ method?: string
19
+ code?: number
20
+ errorKind?: string
21
+ traceId?: string
22
+ }
23
+
24
+ export interface DiagnosticRecord {
25
+ id: string
26
+ timestamp: string
27
+ kind: DiagnosticKind
28
+ message: string
29
+ stack?: string
30
+ version: string
31
+ buildId: string
32
+ route: string
33
+ context: DiagnosticContext
34
+ count: number
35
+ }
36
+
37
+ export type DiagnosticReporter = (record: Readonly<DiagnosticRecord>) => void | Promise<void>
38
+
39
+ const records: DiagnosticRecord[] = []
40
+ const fingerprints = new Map<string, DiagnosticRecord>()
41
+ let reporter: DiagnosticReporter | undefined
42
+ let routeProvider = () => window.location.href
43
+ let sequence = 0
44
+ let reporting = 0
45
+ let windowStart = 0
46
+ let windowCount = 0
47
+
48
+ /** URL 仅保留 origin/path;Hash 路由保留路径,移除查询、锚点和 URL 凭据。 */
49
+ export function diagnosticUrl(value: string): string {
50
+ try {
51
+ const url = new URL(value, window.location.origin)
52
+ if (!['http:', 'https:'].includes(url.protocol)) return `[${url.protocol}]`
53
+ const route = url.hash.startsWith('#/') ? `#${url.hash.slice(1).split(/[?#]/)[0]}` : ''
54
+ return `${url.origin}${url.pathname}${route}`.slice(0, 500)
55
+ } catch {
56
+ return '[invalid URL]'
57
+ }
58
+ }
59
+
60
+ function redact(value: string, max = 1000): string {
61
+ return value
62
+ .replace(/(?:https?:\/\/|\/)[^\s"'<>]+/g, (url) => diagnosticUrl(url))
63
+ .replace(/\bBearer\s+[^\s,;]+/gi, 'Bearer [redacted]')
64
+ .replace(/(\b(?:authorization|cookie)\s*[:=]\s*)[^\r\n]+/gi, '$1[redacted]')
65
+ .replace(
66
+ /(["']?(?:access[_-]?token|refresh[_-]?token|token|password|authorization|cookie|secret)["']?\s*[:=]\s*)(?:"[^"\r\n]*"|'[^'\r\n]*'|[^\s,;}]+)/gi,
67
+ '$1[redacted]'
68
+ )
69
+ .slice(0, max)
70
+ }
71
+
72
+ /** 只接收白名单字段;不收集用户信息、请求头、请求体、响应体或组件实例。 */
73
+ function sanitizeContext(context: DiagnosticContext): DiagnosticContext {
74
+ const result: DiagnosticContext = {}
75
+ for (const key of ['url', 'source'] as const) {
76
+ if (typeof context[key] === 'string') result[key] = diagnosticUrl(context[key])
77
+ }
78
+ for (const key of ['component', 'info', 'method', 'errorKind', 'traceId'] as const) {
79
+ if (typeof context[key] === 'string') result[key] = redact(context[key], 200)
80
+ }
81
+ for (const key of ['line', 'column', 'code'] as const) {
82
+ if (typeof context[key] === 'number' && Number.isFinite(context[key]))
83
+ result[key] = context[key]
84
+ }
85
+ return result
86
+ }
87
+
88
+ export function setDiagnosticReporter(next?: DiagnosticReporter): void {
89
+ reporter = next
90
+ }
91
+
92
+ export function setDiagnosticRouteProvider(provider: () => string): void {
93
+ routeProvider = provider
94
+ }
95
+
96
+ export function getDiagnosticRecords(): DiagnosticRecord[] {
97
+ return records.map((record) => ({ ...record, context: { ...record.context } }))
98
+ }
99
+
100
+ export function clearDiagnosticRecords(): void {
101
+ records.length = 0
102
+ fingerprints.clear()
103
+ }
104
+
105
+ /** 最多保留 50 条;10 秒内重复仅计数;每分钟最多上报 20 条,同时最多 3 条。 */
106
+ export function reportDiagnostic(
107
+ kind: DiagnosticKind,
108
+ error: unknown,
109
+ context: DiagnosticContext = {}
110
+ ): void {
111
+ try {
112
+ const candidate = error as {
113
+ name?: string
114
+ kind?: string
115
+ code?: string
116
+ message?: unknown
117
+ } | null
118
+ if (
119
+ candidate?.name === 'AbortError' ||
120
+ candidate?.name === 'CanceledError' ||
121
+ candidate?.kind === 'cancelled' ||
122
+ candidate?.code === 'ERR_CANCELED'
123
+ )
124
+ return
125
+ const rawMessage =
126
+ error instanceof Error ? error.message : typeof error === 'string' ? error : 'Unknown error'
127
+ if (
128
+ /ResizeObserver loop (?:limit exceeded|completed with undelivered notifications)/.test(
129
+ rawMessage
130
+ )
131
+ )
132
+ return
133
+ const message = redact(rawMessage)
134
+ const sanitized = sanitizeContext(context)
135
+ const stack = error instanceof Error && error.stack ? redact(error.stack, 4000) : undefined
136
+ const route = diagnosticUrl(routeProvider())
137
+ const fingerprint = JSON.stringify([kind, message, stack, route, sanitized])
138
+ const now = Date.now()
139
+ const previous = fingerprints.get(fingerprint)
140
+ if (previous && now - Date.parse(previous.timestamp) < 10000) {
141
+ previous.count++
142
+ return
143
+ }
144
+ const record: DiagnosticRecord = {
145
+ id: `${now.toString(36)}-${++sequence}`,
146
+ timestamp: new Date(now).toISOString(),
147
+ kind,
148
+ message,
149
+ stack,
150
+ version: __APP_VERSION__,
151
+ buildId: typeof __BUILD_ID__ === 'string' ? __BUILD_ID__ : 'dev',
152
+ route,
153
+ context: sanitized,
154
+ count: 1
155
+ }
156
+ records.push(record)
157
+ fingerprints.set(fingerprint, record)
158
+ if (records.length > 50) {
159
+ const removed = records.shift()
160
+ for (const [key, value] of fingerprints) if (value === removed) fingerprints.delete(key)
161
+ }
162
+ console.error('[Diagnostic]', { ...record, context: { ...record.context } })
163
+ if (now - windowStart >= 60000) {
164
+ windowStart = now
165
+ windowCount = 0
166
+ }
167
+ if (!reporter || windowCount >= 20 || reporting >= 3) return
168
+ windowCount++
169
+ reporting++
170
+ const send = reporter
171
+ void Promise.resolve()
172
+ .then(() => send({ ...record, context: { ...record.context } }))
173
+ .catch(() => console.warn('[Diagnostic] 上报失败,记录已保留在本地内存'))
174
+ .finally(() => {
175
+ reporting--
176
+ })
177
+ } catch {
178
+ // 诊断失败不能影响业务,也不能递归进入全局异常处理器。
179
+ }
180
+ }
@@ -1,143 +1,73 @@
1
- /**
2
- * 全局错误处理模块
3
- *
4
- * 提供统一的错误捕获和处理机制
5
- *
6
- * ## 主要功能
7
- *
8
- * - Vue 运行时错误捕获(组件错误、生命周期错误等)
9
- * - 全局脚本错误捕获(语法错误、运行时错误等)
10
- * - Promise 未捕获错误处理(unhandledrejection)
11
- * - 静态资源加载错误监控(图片、脚本、样式等)
12
- * - 错误日志记录和上报
13
- * - 统一的错误处理入口
14
- *
15
- * ## 使用场景
16
- * - 应用启动时安装全局错误处理器
17
- * - 捕获和记录所有类型的错误
18
- * - 错误上报到监控平台
19
- * - 提升应用稳定性和可维护性
20
- * - 问题排查和调试
21
- *
22
- * ## 错误类型
23
- *
24
- * - VueError: Vue 组件相关错误
25
- * - ScriptError: JavaScript 脚本错误
26
- * - PromiseError: Promise 未捕获的 rejection
27
- * - ResourceError: 静态资源加载失败
28
- *
29
- * @module utils/sys/error-handle
30
- * @author Art Design Pro Team
31
- */
32
- import type { App } from 'vue'
1
+ import type { App, ComponentPublicInstance } from 'vue'
2
+ import { reportDiagnostic } from './diagnostics'
33
3
 
34
- const IGNORABLE_SCRIPT_ERRORS = [
35
- 'ResizeObserver loop completed with undelivered notifications.',
36
- 'ResizeObserver loop limit exceeded'
37
- ]
38
-
39
- function normalizeErrorMessage(message: Event | string): string {
40
- if (typeof message === 'string') {
41
- return message
42
- }
43
-
44
- if ('message' in message && typeof message.message === 'string') {
45
- return message.message
46
- }
47
-
48
- return ''
49
- }
50
-
51
- function isIgnorableScriptError(message: Event | string, source?: string): boolean {
52
- const normalizedMessage = normalizeErrorMessage(message)
53
-
54
- if (!normalizedMessage) {
55
- return false
56
- }
57
-
58
- if (IGNORABLE_SCRIPT_ERRORS.some((item) => normalizedMessage.includes(item))) {
59
- // 浏览器/扩展在布局抖动时常见的 ResizeObserver 噪声,不作为真实异常处理
60
- return true
61
- }
62
-
63
- // 浏览器扩展注入脚本偶发的跨域 Script error 也没有排查价值
64
- if (normalizedMessage === 'Script error.' && source === '') {
65
- return true
66
- }
67
-
68
- return false
4
+ export function vueErrorHandler(
5
+ error: unknown,
6
+ instance: ComponentPublicInstance | null,
7
+ info: string
8
+ ): void {
9
+ reportDiagnostic('vue', error, { component: instance?.$options.name, info })
69
10
  }
70
11
 
71
- /**
72
- * Vue 运行时错误处理
73
- */
74
- export function vueErrorHandler(err: unknown, instance: any, info: string) {
75
- console.error('[VueError]', err, info, instance)
76
- // 这里可以上报到服务端,比如:
77
- // reportError({ type: 'vue', err, info })
78
- }
79
-
80
- /**
81
- * 全局脚本错误处理
82
- */
83
12
  export function scriptErrorHandler(
84
13
  message: Event | string,
85
14
  source?: string,
86
- lineno?: number,
87
- colno?: number,
15
+ line?: number,
16
+ column?: number,
88
17
  error?: Error
89
18
  ): boolean {
90
- if (isIgnorableScriptError(message, source)) {
91
- return true
92
- }
19
+ const text = typeof message === 'string' ? message : 'Script error'
20
+ if (text === 'Script error.' && !source) return false
21
+ reportDiagnostic('script', error ?? text, { source, line, column })
22
+ // 保留浏览器默认报错,便于生产环境排查。
23
+ return false
24
+ }
93
25
 
94
- console.error('[ScriptError]', { message, source, lineno, colno, error })
95
- // reportError({ type: 'script', message, source, lineno, colno, error })
96
- return true // 阻止默认控制台报错,可根据需求改
26
+ export function registerPromiseErrorHandler(): () => void {
27
+ const listener = (event: PromiseRejectionEvent) => reportDiagnostic('promise', event.reason)
28
+ window.addEventListener('unhandledrejection', listener)
29
+ return () => window.removeEventListener('unhandledrejection', listener)
97
30
  }
98
31
 
99
- /**
100
- * Promise 未捕获错误处理
101
- */
102
- export function registerPromiseErrorHandler() {
103
- window.addEventListener('unhandledrejection', (event) => {
104
- console.error('[PromiseError]', event.reason)
105
- // reportError({ type: 'promise', reason: event.reason })
106
- })
32
+ export function registerResourceErrorHandler(): () => void {
33
+ const listener = (event: Event) => {
34
+ const target = event.target
35
+ if (
36
+ target instanceof HTMLImageElement ||
37
+ target instanceof HTMLScriptElement ||
38
+ target instanceof HTMLLinkElement
39
+ ) {
40
+ reportDiagnostic('resource', `${target.tagName} load failed`, {
41
+ url: target instanceof HTMLLinkElement ? target.href : target.src
42
+ })
43
+ }
44
+ }
45
+ window.addEventListener('error', listener, true)
46
+ return () => window.removeEventListener('error', listener, true)
107
47
  }
108
48
 
109
- /**
110
- * 资源加载错误处理 (img, script, css...)
111
- */
112
- export function registerResourceErrorHandler() {
113
- window.addEventListener(
114
- 'error',
115
- (event: Event) => {
116
- const target = event.target as HTMLElement
117
- if (
118
- target &&
119
- (target.tagName === 'IMG' || target.tagName === 'SCRIPT' || target.tagName === 'LINK')
120
- ) {
121
- console.error('[ResourceError]', {
122
- tagName: target.tagName,
123
- src:
124
- (target as HTMLImageElement).src ||
125
- (target as HTMLScriptElement).src ||
126
- (target as HTMLLinkElement).href
127
- })
128
- // reportError({ type: 'resource', target })
129
- }
130
- },
131
- true // 捕获阶段才能监听到资源错误
132
- )
49
+ let dispose: (() => void) | undefined
50
+
51
+ /** 在应用初始化之前安装;重复安装不会叠加监听器。 */
52
+ export function setupGlobalErrorHandlers(): () => void {
53
+ if (dispose) return dispose
54
+ const onError = (event: ErrorEvent) => {
55
+ if (event instanceof ErrorEvent)
56
+ scriptErrorHandler(event.message, event.filename, event.lineno, event.colno, event.error)
57
+ }
58
+ window.addEventListener('error', onError)
59
+ const removePromise = registerPromiseErrorHandler()
60
+ const removeResource = registerResourceErrorHandler()
61
+ dispose = () => {
62
+ window.removeEventListener('error', onError)
63
+ removePromise()
64
+ removeResource()
65
+ dispose = undefined
66
+ }
67
+ return dispose
133
68
  }
134
69
 
135
- /**
136
- * 安装统一错误处理
137
- */
138
- export function setupErrorHandle(app: App) {
70
+ export function setupErrorHandle(app: App): void {
71
+ setupGlobalErrorHandlers()
139
72
  app.config.errorHandler = vueErrorHandler
140
- window.onerror = scriptErrorHandler
141
- registerPromiseErrorHandler()
142
- registerResourceErrorHandler()
143
73
  }
@@ -0,0 +1,31 @@
1
+ import { ref } from 'vue'
2
+
3
+ export const resourceRecoveryNeeded = ref(false)
4
+ let failedPath = '/'
5
+
6
+ export function isChunkLoadError(error: unknown): boolean {
7
+ return (
8
+ error instanceof Error &&
9
+ /Loading (?:CSS )?chunk|ChunkLoadError|Failed to fetch dynamically imported module|Importing a module script failed|error loading dynamically imported module|Unable to preload CSS/i.test(
10
+ `${error.name}: ${error.message}`
11
+ )
12
+ )
13
+ }
14
+
15
+ export function markResourceFailure(path?: string): void {
16
+ resourceRecoveryNeeded.value = true
17
+ if (path?.startsWith('/') && !path.startsWith('//')) failedPath = path
18
+ }
19
+
20
+ export function clearResourceFailure(): void {
21
+ resourceRecoveryNeeded.value = false
22
+ failedPath = '/'
23
+ }
24
+
25
+ /** 仅由用户点击触发,恢复失败地址后整页刷新,不做自动循环刷新。 */
26
+ export function reloadFailedPage(): void {
27
+ const url = new URL(window.location.href)
28
+ url.hash = `#${failedPath}`
29
+ window.history.replaceState(window.history.state, '', url)
30
+ window.location.reload()
31
+ }
@@ -4,13 +4,21 @@
4
4
  <div>
5
5
  <span>FOUNDATION / ACCESS CONTROL</span>
6
6
  <h1 id="permission-title">权限演练场</h1>
7
- <p>同时验证路由元数据、操作权限和角色权限。演示身份来自 Mock 认证适配器。</p>
7
+ <p>路由、指令和组合式函数使用同一套用户授权,权限变化后立即更新。</p>
8
8
  </div>
9
9
  <div class="identity" aria-label="当前演示身份">
10
10
  <ArtSvgIcon icon="ri:shield-user-line" aria-hidden="true" />
11
11
  <div
12
12
  ><small>当前身份</small><strong>{{ userName }}</strong></div
13
13
  >
14
+ <ElSelect v-if="isMock" v-model="demoProfile" aria-label="演示身份" style="width: 150px">
15
+ <ElOption
16
+ v-for="profile in profiles"
17
+ :key="profile.id"
18
+ :label="profile.name"
19
+ :value="profile.id"
20
+ />
21
+ </ElSelect>
14
22
  </div>
15
23
  </section>
16
24
 
@@ -29,15 +37,24 @@
29
37
  <div class="section-heading">
30
38
  <div
31
39
  ><h2 id="operation-title">操作权限</h2
32
- ><p>当前路由开放 create、edit 和 export,approve 按钮会被指令从 DOM 移除。</p></div
40
+ ><p>按钮根据用户授权显示或禁用;页面动作声明本身不会授予权限。</p></div
33
41
  >
34
- <ElTag type="success" effect="light">3 项可用</ElTag>
42
+ <ElTag effect="light">{{ availableCount }} 项可用</ElTag>
35
43
  </div>
36
44
  <div class="button-row">
37
- <ElButton v-auth="'create'" type="primary" @click="notify('create')">新增资源</ElButton>
38
- <ElButton v-auth="'edit'" @click="notify('edit')">编辑资源</ElButton>
39
- <ElButton v-auth="'export'" @click="notify('export')">导出数据</ElButton>
40
- <ElButton v-auth="'approve'" type="warning">审核资源</ElButton>
45
+ <ElButton v-auth="'example:resource:create'" type="primary" @click="notify('create')"
46
+ >新增资源</ElButton
47
+ >
48
+ <ElButton v-permission="'example:resource:edit'" @click="notify('edit')">编辑资源</ElButton>
49
+ <ElButton v-if="hasPermission('example:resource:export')" @click="notify('export')"
50
+ >导出数据</ElButton
51
+ >
52
+ <ElButton
53
+ v-permission.disabled="'example:resource:approve'"
54
+ type="warning"
55
+ @click="notify('approve')"
56
+ >审核资源</ElButton
57
+ >
41
58
  </div>
42
59
  <ElAlert title="安全提示" type="info" :closable="false" show-icon>
43
60
  <template #default>前端权限只控制界面可见性,真实接口仍必须在服务端执行鉴权。</template>
@@ -48,7 +65,7 @@
48
65
  <div class="section-heading"
49
66
  ><div
50
67
  ><h2 id="role-title">角色权限</h2
51
- ><p>Mock 管理员拥有 R_SUPER,审计员专属内容不会渲染。</p></div
68
+ ><p>角色约束独立于操作权限;切换演示身份可观察区域的隐藏与恢复。</p></div
52
69
  ></div
53
70
  >
54
71
  <div class="role-cards">
@@ -60,7 +77,7 @@
60
77
  <article v-roles="'R_AUDITOR'" class="role-card"><strong>审计员区域</strong></article>
61
78
  <article class="role-card is-denied"
62
79
  ><ArtSvgIcon icon="ri:forbid-line" /><div
63
- ><strong>审计员区域</strong><p>角色不匹配,实际受控节点已从 DOM 移除。</p></div
80
+ ><strong>审计员区域</strong><p>角色不匹配,受控区域会随当前角色更新。</p></div
64
81
  ></article
65
82
  >
66
83
  </div>
@@ -71,20 +88,58 @@
71
88
  <script setup lang="ts">
72
89
  import { ElMessage } from 'element-plus'
73
90
  import { useUserStore } from '@/store/modules/user'
91
+ import { usePermission } from '@/hooks/core/usePermission'
92
+ import { authAdapter } from '@/adapters/auth'
74
93
  defineOptions({ name: 'PermissionPlaygroundExample' })
75
94
  const userStore = useUserStore()
76
95
  const userName = computed(() => userStore.getUserInfo.userName || '模板管理员')
96
+ const { hasPermission } = usePermission()
97
+ const isMock = authAdapter.name === 'mock'
98
+ const actions = ['create', 'edit', 'export', 'approve']
99
+ const availableCount = computed(
100
+ () => actions.filter((action) => hasPermission(`example:resource:${action}`)).length
101
+ )
102
+ const profiles = [
103
+ { id: 'admin', name: '模板管理员', roles: ['R_SUPER'], permissions: ['*:*:*'] },
104
+ {
105
+ id: 'member',
106
+ name: '普通成员',
107
+ roles: ['R_USER'],
108
+ permissions: [
109
+ 'example:resource:create',
110
+ 'example:resource:edit',
111
+ 'example:resource:export',
112
+ 'example:navigation:read'
113
+ ]
114
+ },
115
+ { id: 'empty', name: '无操作权限', roles: [], permissions: [] }
116
+ ]
117
+ const demoProfile = computed({
118
+ get: () => profiles.find((profile) => profile.name === userName.value)?.id ?? 'admin',
119
+ set: (id: string) => {
120
+ const profile = profiles.find((item) => item.id === id)
121
+ if (profile && isMock)
122
+ userStore.setUserInfo({
123
+ ...userStore.info,
124
+ userId: 'admin',
125
+ userName: profile.name,
126
+ email: 'admin@example.com',
127
+ roles: profile.roles,
128
+ permissions: profile.permissions
129
+ })
130
+ }
131
+ })
77
132
  const permissionLayers = [
78
133
  {
79
134
  title: '路由层',
80
- description: '通过 roles 决定页面是否可以注册和访问。',
81
- code: 'meta.roles',
135
+ description: '路由声明角色或权限要求,每次导航都执行校验。',
136
+ code: 'meta.roles / permissions',
82
137
  icon: 'ri:route-line'
83
138
  },
84
139
  {
85
140
  title: '操作层',
86
- description: '通过路由 authList 控制页面内具体操作。',
87
- code: 'v-auth',
141
+ description: '指令与 hasPermission 共用用户权限集合。',
142
+ code: 'v-permission / hasPermission',
88
143
  icon: 'ri:cursor-line'
89
144
  },
90
145
  {
@@ -142,6 +197,7 @@
142
197
  .identity {
143
198
  display: flex;
144
199
  flex: 0 0 auto;
200
+ flex-wrap: wrap;
145
201
  gap: 12px;
146
202
  align-items: center;
147
203
  min-width: 190px;
@@ -1,6 +1,15 @@
1
1
  <!-- 403页面 -->
2
2
  <template>
3
+ <main v-if="hasNoAccess" class="page-content">
4
+ <KvStatus
5
+ :title="$t('access.noAccessTitle')"
6
+ :description="errorMessage || $t('access.noAccessDescription')"
7
+ :action-text="$t(refreshing ? 'access.checking' : 'access.checkAgain')"
8
+ @action="checkAgain"
9
+ />
10
+ </main>
3
11
  <ArtException
12
+ v-else
4
13
  :data="{
5
14
  title: '403',
6
15
  desc: $t('exceptionPage.403'),
@@ -11,6 +20,30 @@
11
20
  </template>
12
21
 
13
22
  <script setup lang="ts">
23
+ import { ref, computed } from 'vue'
24
+ import { KvStatus } from '@kevairy/components'
25
+ import { useUserStore } from '@/store/modules/user'
26
+ import { useMenuStore } from '@/store/modules/menu'
27
+ import { refreshAccess } from '@/services/permission'
14
28
  import imgUrl from '@imgs/svg/403.svg'
15
29
  defineOptions({ name: 'Exception403' })
30
+ const user = useUserStore()
31
+ const menus = useMenuStore()
32
+ const hasNoAccess = computed(
33
+ () => user.isLogin && user.permissionsReady && menus.menuList.length === 0
34
+ )
35
+ const refreshing = ref(false)
36
+ const errorMessage = ref('')
37
+ const checkAgain = async () => {
38
+ if (refreshing.value) return
39
+ refreshing.value = true
40
+ errorMessage.value = ''
41
+ try {
42
+ await refreshAccess()
43
+ } catch (error) {
44
+ errorMessage.value = error instanceof Error ? error.message : String(error)
45
+ } finally {
46
+ refreshing.value = false
47
+ }
48
+ }
16
49
  </script>
@@ -1,16 +1,58 @@
1
- <!-- 500页面 -->
2
1
  <template>
3
- <ArtException
4
- :data="{
5
- title: '500',
6
- desc: $t('exceptionPage.500'),
7
- btnText: $t('exceptionPage.gohome'),
8
- imgUrl
9
- }"
10
- />
2
+ <main class="page-content">
3
+ <KvStatus
4
+ type="error"
5
+ title="500"
6
+ :description="
7
+ errorMessage ||
8
+ $t(
9
+ resourceRecoveryNeeded
10
+ ? 'exceptionPage.resourceFailure'
11
+ : 'exceptionPage.retryDescription'
12
+ )
13
+ "
14
+ :action-text="
15
+ $t(
16
+ retrying
17
+ ? 'access.checking'
18
+ : resourceRecoveryNeeded
19
+ ? 'exceptionPage.reload'
20
+ : 'exceptionPage.retry'
21
+ )
22
+ "
23
+ @action="retry"
24
+ />
25
+ </main>
11
26
  </template>
12
27
 
13
28
  <script setup lang="ts">
14
- import imgUrl from '@imgs/svg/500.svg'
29
+ import { ref } from 'vue'
30
+ import { KvStatus } from '@kevairy/components'
31
+ import { router } from '@/router'
32
+ import { resetRouterState } from '@/router/guards/beforeEach'
33
+ import { useUserStore } from '@/store/modules/user'
34
+ import { resourceRecoveryNeeded, reloadFailedPage } from '@/utils/sys/recovery'
35
+ import { isRequestCanceled } from '@/utils/http/error'
36
+
15
37
  defineOptions({ name: 'Exception500' })
38
+ const retrying = ref(false)
39
+ const errorMessage = ref('')
40
+ const retry = async () => {
41
+ if (retrying.value) return
42
+ if (resourceRecoveryNeeded.value) {
43
+ reloadFailedPage()
44
+ return
45
+ }
46
+ retrying.value = true
47
+ errorMessage.value = ''
48
+ try {
49
+ resetRouterState(0)
50
+ await router.replace(useUserStore().isLogin ? '/' : '/auth/login')
51
+ } catch (error) {
52
+ if (!isRequestCanceled(error))
53
+ errorMessage.value = error instanceof Error ? error.message : String(error)
54
+ } finally {
55
+ retrying.value = false
56
+ }
57
+ }
16
58
  </script>