Enforce requiresAuth routes in global router guard with login return-to redirects
Co-Authored-By: Codex <codex@openai.com>
This commit is contained in:
@@ -18,18 +18,34 @@ describe("router beforeEach guard logic", () => {
|
||||
|
||||
// Simulate the guard logic from router/index.ts
|
||||
function runGuard(to) {
|
||||
const isLoggedIn = document.cookie
|
||||
const hasLoginMarker = document.cookie
|
||||
.split(";")
|
||||
.some((c) => c.trim().startsWith("isLuciaLoggedIn="));
|
||||
const hasAccessToken = document.cookie
|
||||
.split(";")
|
||||
.some((c) => c.trim().startsWith("luciaToken="));
|
||||
const isAuthenticated = hasLoginMarker && hasAccessToken;
|
||||
|
||||
if (to.name === "Login") {
|
||||
if (isLoggedIn) return { name: "Files" };
|
||||
if (isAuthenticated) return { name: "Files" };
|
||||
}
|
||||
|
||||
const requiresAuth = (to.matched || []).some((r) => r.meta?.requiresAuth);
|
||||
if (requiresAuth && !isAuthenticated) {
|
||||
return {
|
||||
path: "/login",
|
||||
query: {
|
||||
"return-to": btoa(to.fullPath || to.path || "/"),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
it("redirects logged-in user from Login to Files", () => {
|
||||
document.cookie = "isLuciaLoggedIn=true";
|
||||
document.cookie = "luciaToken=token";
|
||||
expect(runGuard({ name: "Login" })).toEqual({ name: "Files" });
|
||||
});
|
||||
|
||||
@@ -37,8 +53,27 @@ describe("router beforeEach guard logic", () => {
|
||||
expect(runGuard({ name: "Login" })).toBeUndefined();
|
||||
});
|
||||
|
||||
it("redirects unauthenticated user when route requiresAuth", () => {
|
||||
const result = runGuard({
|
||||
name: "Files",
|
||||
path: "/files",
|
||||
fullPath: "/files",
|
||||
matched: [{ meta: { requiresAuth: true } }],
|
||||
});
|
||||
expect(result.path).toBe("/login");
|
||||
expect(atob(result.query["return-to"])).toBe("/files");
|
||||
});
|
||||
|
||||
it("does not interfere with non-Login routes", () => {
|
||||
document.cookie = "isLuciaLoggedIn=true";
|
||||
expect(runGuard({ name: "Files" })).toBeUndefined();
|
||||
document.cookie = "luciaToken=token";
|
||||
expect(
|
||||
runGuard({
|
||||
name: "Files",
|
||||
path: "/files",
|
||||
fullPath: "/files",
|
||||
matched: [{ meta: { requiresAuth: true } }],
|
||||
}),
|
||||
).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user