Files
OCS_service/app/middleware/auth.ts
T
2026-05-22 22:38:01 +08:00

23 lines
769 B
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// app/middleware/auth.ts - 路由守卫,未登录时重定向到登录页
import { useAuthStore } from "@/stores/auth";
export default defineNuxtRouteMiddleware(async (to) => {
// 只保护 /dashboard 路径
if (!to.path.startsWith("/dashboard")) return;
// SSR 阶段无浏览器 cookiesession 由 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");
}
});