Enforce requiresAuth routes in global router guard with login return-to redirects
Co-Authored-By: Codex <codex@openai.com>
This commit is contained in:
@@ -10,6 +10,8 @@
|
||||
*/
|
||||
|
||||
import { createRouter, createWebHistory } from "vue-router";
|
||||
import { useLoginStore } from "@/stores/login";
|
||||
import { getCookie, setCookie } from "@/utils/cookieUtil";
|
||||
import AuthContainer from "@/views/AuthContainer.vue";
|
||||
import MainContainer from "@/views/MainContainer.vue";
|
||||
import Login from "@/views/Login/LoginPage.vue";
|
||||
@@ -171,18 +173,51 @@ const router = createRouter({
|
||||
routes,
|
||||
});
|
||||
|
||||
/**
|
||||
* Builds a login redirect target with a return-to query.
|
||||
* @param {string} fullPath - The destination path to return after login.
|
||||
* @returns {{path: string, query: {"return-to": string}}} The redirect target.
|
||||
*/
|
||||
function buildLoginRedirect(fullPath: string) {
|
||||
return {
|
||||
path: "/login",
|
||||
query: {
|
||||
"return-to": btoa(fullPath),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Global navigation guard
|
||||
router.beforeEach((to, from) => {
|
||||
router.beforeEach(async (to) => {
|
||||
// to: Route: the target route object being navigated to
|
||||
// from: Route: the current route being navigated away from
|
||||
const hasLoginMarker = Boolean(getCookie("isLuciaLoggedIn"));
|
||||
const hasAccessToken = Boolean(getCookie("luciaToken"));
|
||||
const hasRefreshToken = Boolean(getCookie("luciaRefreshToken"));
|
||||
const isAuthenticated = hasLoginMarker && hasAccessToken;
|
||||
|
||||
// When navigating to the login page, redirect to Files if already logged in
|
||||
if (to.name === "Login") {
|
||||
const isLoggedIn = document.cookie
|
||||
.split(";")
|
||||
.some((c) => c.trim().startsWith("isLuciaLoggedIn="));
|
||||
if (isLoggedIn) return { name: "Files" };
|
||||
if (to.name === "Login" && isAuthenticated) {
|
||||
return { name: "Files" };
|
||||
}
|
||||
|
||||
const requiresAuth = to.matched.some((routeRecord) => routeRecord.meta.requiresAuth);
|
||||
if (!requiresAuth || isAuthenticated) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (hasRefreshToken) {
|
||||
const loginStore = useLoginStore();
|
||||
try {
|
||||
await loginStore.refreshToken();
|
||||
loginStore.setIsLoggedIn(true);
|
||||
setCookie("isLuciaLoggedIn", "true");
|
||||
return undefined;
|
||||
} catch {
|
||||
return buildLoginRedirect(to.fullPath);
|
||||
}
|
||||
}
|
||||
|
||||
return buildLoginRedirect(to.fullPath);
|
||||
});
|
||||
|
||||
export default router;
|
||||
|
||||
Reference in New Issue
Block a user