feat: 优化
This commit is contained in:
@@ -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
|
||||
})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user