feat: 新增鉴权
This commit is contained in:
@@ -0,0 +1,22 @@
|
||||
// app/middleware/auth.ts - 路由守卫,未登录时重定向到登录页
|
||||
import { useAuthStore } from "@/stores/auth";
|
||||
|
||||
export default defineNuxtRouteMiddleware(async (to) => {
|
||||
// 只保护 /dashboard 路径
|
||||
if (!to.path.startsWith("/dashboard")) return;
|
||||
|
||||
// SSR 阶段无浏览器 cookie,session 由 auth.client.ts 插件在客户端初始化
|
||||
// 服务端直接放行,客户端插件执行完毕后 middleware 会带着正确状态再次运行
|
||||
if (import.meta.server) return;
|
||||
|
||||
const authStore = useAuthStore();
|
||||
|
||||
// 等待 session 初始化完成(插件已发起,此处复用同一 Promise 去重)
|
||||
if (!authStore.initialized) {
|
||||
await authStore.fetchSession();
|
||||
}
|
||||
|
||||
if (!authStore.isOnline) {
|
||||
return navigateTo("/login");
|
||||
}
|
||||
});
|
||||
Reference in New Issue
Block a user