/// <reference types="@uni-helper/vite-plugin-uni-pages/client" />
|
import { pages, subPackages } from 'virtual:uni-pages'
|
import { fetchMiniMe } from '@/api/auth'
|
import { setUnauthorizedRedirectHandler } from './authRedirect'
|
import { clearMiniAuthSession, getPersistedAuthState, showMiniLoginPrompt, updateMiniAuthProfile } from '@/store/auth'
|
import { normalizeMeProfile } from '@/types/auth'
|
|
function generateRoutes() {
|
const routes = pages.map((page) => {
|
const newPath = `/${page.path}`
|
return { ...page, path: newPath }
|
})
|
if (subPackages && subPackages.length > 0) {
|
subPackages.forEach((subPackage) => {
|
const subRoutes = subPackage.pages.map((page: any) => {
|
const newPath = `/${subPackage.root}/${page.path}`
|
return { ...page, path: newPath }
|
})
|
routes.push(...subRoutes)
|
})
|
}
|
return routes
|
}
|
|
const router = createRouter({
|
routes: generateRoutes(),
|
})
|
|
setUnauthorizedRedirectHandler(() => {
|
showMiniLoginPrompt('登录已失效,请重新登录')
|
router.replaceAll({ name: 'home' })
|
})
|
|
const PUBLIC_ROUTE_NAMES = new Set(['home', 'login', 'visitorCode'])
|
const HOME_ROUTE_NAME = 'home'
|
|
function isPublicRoute(name?: string) {
|
return Boolean(name && PUBLIC_ROUTE_NAMES.has(name))
|
}
|
|
router.beforeEach((to, from, next) => {
|
const state = getPersistedAuthState()
|
const hasToken = Boolean(state.token)
|
const hasProfile = Boolean(state.profile)
|
const publicRoute = isPublicRoute(to.name)
|
|
if (!hasToken) {
|
if (publicRoute) {
|
next()
|
return
|
}
|
showMiniLoginPrompt('您还未登录,请先登录')
|
next({ name: HOME_ROUTE_NAME })
|
return
|
}
|
|
const ensureProfile = async () => {
|
if (hasProfile) {
|
return true
|
}
|
try {
|
const profile = await fetchMiniMe()
|
updateMiniAuthProfile(normalizeMeProfile(profile))
|
return true
|
}
|
catch (error) {
|
console.warn('mini auth guard fetch /me failed', error)
|
clearMiniAuthSession()
|
showMiniLoginPrompt('登录已失效,请重新登录')
|
return false
|
}
|
}
|
|
return Promise.resolve(ensureProfile()).then((ok) => {
|
if (!ok) {
|
next({ name: HOME_ROUTE_NAME })
|
return
|
}
|
if (to.name === 'login') {
|
next({ name: HOME_ROUTE_NAME })
|
return
|
}
|
next()
|
})
|
})
|
|
router.afterEach((to, from) => {
|
if (import.meta.env.MODE === 'development' && to.path) {
|
console.log(`📄 页面切换完成: ${from.path || '-'} -> ${to.path}`)
|
}
|
})
|
|
export default router
|