Files
datahub/frontend/src/main.ts
T

68 lines
1.6 KiB
TypeScript
Raw Normal View History

2025-11-05 16:34:40 +08:00
import './assets/main.css'
2025-11-10 11:07:48 +08:00
import 'ant-design-vue/dist/reset.css'
2025-11-05 16:34:40 +08:00
import { createApp } from 'vue'
import { createPinia } from 'pinia'
2025-11-10 11:07:48 +08:00
import { createRouter, createWebHistory } from 'vue-router'
import { routes } from 'vue-router/auto-routes'
2025-11-05 16:34:40 +08:00
import App from './App.vue'
import { setTokenGetter } from './utils/request'
2026-04-03 15:13:24 +08:00
import { isAdminOnlyPath } from '@/constants/permissions'
2025-11-10 11:07:48 +08:00
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes,
})
2025-11-05 16:34:40 +08:00
2026-03-18 13:53:36 +08:00
const pinia = createPinia()
2025-11-05 16:34:40 +08:00
const app = createApp(App)
2026-03-18 13:53:36 +08:00
app.use(pinia)
2025-11-05 16:34:40 +08:00
app.use(router)
// 注入 token 获取函数,使 request.ts 能读取内存中的 tokenremember=false 场景)
import { useUserStore } from './stores/user'
setTokenGetter(() => useUserStore().token)
2026-03-18 13:53:36 +08:00
// 路由守卫
const authWhitelist = ['/login', '/register']
router.beforeEach(async (to) => {
const { useUserStore } = await import('./stores/user')
const userStore = useUserStore()
// 白名单页面(登录/注册)
if (authWhitelist.includes(to.path)) {
if (userStore.isLoggedIn) {
return '/'
}
return true
}
// 未登录跳转登录页
if (!userStore.isLoggedIn) {
return `/login?redirect=${to.fullPath}`
}
// 已登录但未获取用户信息
if (!userStore.user) {
try {
await userStore.fetchCurrentUser()
} catch {
userStore.logout()
return '/login'
}
}
2026-04-03 15:13:24 +08:00
// 角色权限检查:非 admin 不能访问受限路由(前缀匹配)
if (isAdminOnlyPath(to.path) && !userStore.isAdmin) {
2026-03-19 08:44:32 +08:00
message.error('无权访问')
return '/'
}
2026-03-18 13:53:36 +08:00
return true
})
2025-11-05 16:34:40 +08:00
app.mount('#app')