You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

23 lines
684 B
TypeScript

1 month ago
// middleware/auth.ts
import { useAuthStore } from '~/stores/auth'
export default defineNuxtRouteMiddleware(async (to, from) => {
const authStore = useAuthStore()
// 检查是否需要认证
const publicPages = ['/login']
const isPublicPage = publicPages.includes(to.path)
// 如果不是公共页面且未认证,重定向到登录页
if (!isPublicPage && !authStore.isAuthenticated) {
const checked = await authStore.checkAuth()
if (!checked) {
return navigateTo('/login')
}
}
// 如果已认证且访问登录页,重定向到首页
if (isPublicPage && authStore.isAuthenticated && to.path === '/login') {
return navigateTo('/')
}
})