feat: 优化

This commit is contained in:
2026-03-28 17:08:06 +08:00
parent 7b3da62bc2
commit cf1e3667ec

View File

@@ -5,26 +5,33 @@ import { storeToRefs } from 'pinia'
import pinia from '@/plugins/pinia/setup'
import { useAuthStore } from '@/stores/auth'
// 需要认证的路由前缀
const AUTH_ROUTES = ['/monisuo/', '/dashboard', '/users', '/tasks', '/settings']
// 需要认证的白名单路由
const WHITE_LIST = ['/auth/sign-in', '/auth/sign-up', '/auth/forgot-password']
export function authGuard(router: Router) {
router.beforeEach((to, _from) => {
const authStore = useAuthStore(pinia)
const { isLogin } = storeToRefs(authStore)
// 检查是否是需要认证的路由
const needsAuth = to.meta.auth || AUTH_ROUTES.some(prefix => to.path.startsWith(prefix))
// 检查是否在白名单中
const isInWhiteList = WHITE_LIST.some(path => to.path === path || to.path.startsWith(path + '/'))
console.log('[AuthGuard]', to.path, 'needsAuth:', needsAuth, 'isLogin:', unref(isLogin))
console.log('[AuthGuard]', to.path, 'isInWhiteList:', isInWhiteList, 'isLogin:', unref(isLogin))
// 如果页面需要登录但用户未登录,重定向到登录页并记录原始目标页面
if (needsAuth && !unref(isLogin) && to.name !== '/auth/sign-in') {
// 如果已登录且访问登录,重定向到首页
if (unref(isLogin) && to.path === '/auth/sign-in') {
return { name: '/monisuo/dashboard' }
}
// 如果未登录且不在白名单中,重定向到登录页
if (!unref(isLogin) && !isInWhiteList) {
console.log('[AuthGuard] Redirecting to login')
return {
name: '/auth/sign-in',
query: { redirect: to.fullPath },
}
}
return true
})
}