fix: 恢復 router redirect 指向
This commit is contained in:
parent
c92dee5213
commit
3884f139aa
BIN
src/router/index-84b479b.js
Normal file
BIN
src/router/index-84b479b.js
Normal file
Binary file not shown.
@ -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;
|
||||
|
Loading…
Reference in New Issue
Block a user