This commit is contained in:
2026-03-22 14:22:57 +08:00
parent c41154c93a
commit 7325106ae7
6 changed files with 147 additions and 21 deletions

View File

@@ -5,33 +5,22 @@ import { storeToRefs } from 'pinia'
import pinia from '@/plugins/pinia/setup'
import { useAuthStore } from '@/stores/auth'
// 需要认证的 Monisuo 路由前缀
const MONISUO_AUTH_ROUTES = ['/monisuo/']
// 需要认证的路由前缀
const AUTH_ROUTES = ['/monisuo/', '/dashboard', '/users', '/tasks', '/settings']
export function authGuard(router: Router) {
router.beforeEach((to, _from) => {
const authStore = useAuthStore(pinia)
const { isLogin } = storeToRefs(authStore)
// 检查是否是需要认证的 Monisuo 路由
const isMonisuoRoute = MONISUO_AUTH_ROUTES.some(prefix => to.path.startsWith(prefix))
// 检查是否是需要认证的路由
const needsAuth = to.meta.auth || AUTH_ROUTES.some(prefix => to.path.startsWith(prefix))
// 如果页面需要登录但用户未登录,重定向到登录页并记录原始目标页面
if ((to.meta.auth || isMonisuoRoute) && !unref(isLogin)) {
// Monisuo 路由重定向到 Monisuo 登录页
if (isMonisuoRoute && to.name !== '/auth/monisuo-sign-in') {
return {
name: '/auth/monisuo-sign-in',
query: { redirect: to.fullPath },
}
}
// 其他需要认证的路由重定向到默认登录页
if (to.meta.auth && to.name !== '/auth/sign-in') {
return {
name: '/auth/sign-in',
query: { redirect: to.fullPath },
}
if (needsAuth && !unref(isLogin) && to.name !== '/auth/sign-in') {
return {
name: '/auth/sign-in',
query: { redirect: to.fullPath },
}
}
})