Files
webgame-frontend/src/router/guard.ts
T

65 lines
1.8 KiB
TypeScript
Raw Normal View History

2026-06-02 13:38:43 +08:00
import type { Router } from 'vue-router'
2026-06-16 16:16:47 +08:00
import { useAccountStore } from '@/stores'
/** 无需登录即可访问的路由路径前缀 */
const PUBLIC_PATHS = ['/auth']
/**
* 判断目标路由是否为公开路由(无需登录)
* @param path - 目标路由路径
*/
function isPublicPath(path: string): boolean {
return PUBLIC_PATHS.some((prefix) => path.startsWith(prefix))
}
2026-06-02 13:38:43 +08:00
/**
* 通用路由守卫
2026-06-16 16:16:47 +08:00
* - 首次导航时验证 token 是否有效
* - 未登录用户访问非公开路由 → 跳转登录页
* - 已登录用户访问登录相关页面 → 跳转首页
2026-06-02 13:38:43 +08:00
*/
function setupCommonGuard(router: Router) {
2026-06-16 16:16:47 +08:00
router.beforeEach(async (to) => {
const accountStore = useAccountStore()
// 已登录用户访问公开路由(如登录页),直接跳转首页
2026-06-17 12:23:23 +08:00
if (!!accountStore.accessToken && isPublicPath(to.path)) {
2026-06-16 16:16:47 +08:00
return '/'
}
2026-06-17 12:23:23 +08:00
// accessToken 检查
if (!accountStore.accessToken) {
// 明确声明忽略权限访问权限,则可以访问
if (to.meta.ignoreAccess) {
return true
}
// 未登录用户访问非公开路由,跳转登录页
if (!isPublicPath(to.path)) {
// 将原本要访问的路径作为 redirect 参数传递,登录后可跳回
return { path: '/auth/login', query: { redirect: to.fullPath }, replace: true }
}
// 没有访问权限,跳转登录页面
if (to.fullPath !== '/auth/login') {
return {
path: '/auth/login',
query: { redirect: to.fullPath },
// 携带当前跳转的页面,登录后重新跳转该页面
replace: true
}
}
return to
2026-06-16 16:16:47 +08:00
}
2026-06-02 13:38:43 +08:00
return true
})
}
// 路由守卫
function createRouterGuard(router: Router) {
setupCommonGuard(router)
}
export { createRouterGuard }