diff --git a/src/router/index-84b479b.js b/src/router/index-84b479b.js new file mode 100644 index 0000000..01b98c5 Binary files /dev/null and b/src/router/index-84b479b.js differ diff --git a/src/router/index.js b/src/router/index.js index 290953e..49db595 100644 --- a/src/router/index.js +++ b/src/router/index.js @@ -79,49 +79,38 @@ const router = createRouter({ ], }); -router.beforeEach((to, from, next) => { +router.beforeEach(async (to, from, next) => { console.log("route", to, location, document.cookie); + // redirect to login page if not logged in and trying to access a restricted page const publicPages = ["/login", "/"]; - const requiresAuth = !publicPages.includes(to.path); - + const authRequired = !publicPages.includes(to.path); const auth = useUserInfoStore(); const token = useGetCookie("JWT-Authorization"); const user_name = useGetCookie("user_name"); - // 處理 /logout if (to.path === "/logout") { - // 清除 cookie(建議補 Path 與 SameSite) - document.cookie = "JWT-Authorization=; Max-Age=0; Path=/"; - document.cookie = "user_name=; Max-Age=0; Path=/"; - - // 清除狀態 + document.cookie = "JWT-Authorization=; Max-Age=0"; + document.cookie = "user_name=; Max-Age=0"; auth.user.token = ""; auth.user.user_name = ""; localStorage.removeItem("EmpowerBuilding"); - - // 直接導回登入(避免 reload 與 next() 交疊) - return next({ path: "/login", replace: true }); + window.location.reload(); + next({ path: "/login" }); } - // 未登入:擋住受保護頁 - if (requiresAuth && !token) { + if ((authRequired && !token) || to.path === "/") { auth.user.token = ""; - return next({ path: "/login", replace: true }); - } - - // 進公開頁(例如 /login):清掉使用者狀態(若你想保留語系就不要清) - if (!requiresAuth) { - document.cookie = "JWT-Authorization=; Max-Age=0; Path=/"; - document.cookie = "user_name=; Max-Age=0; Path=/"; + next({ path: "/login" }); + } else if (!authRequired) { + document.cookie = "JWT-Authorization=; Max-Age=0"; + document.cookie = "user_name=; Max-Age=0"; auth.user.token = ""; auth.user.user_name = ""; - return next(); + } else { + auth.user.token = token; + auth.user.user_name = user_name; } - - // 受保護頁且有 token:同步 Pinia 狀態 - auth.user.token = token; - auth.user.user_name = user_name; - return next(); + next(); }); export default router;