Extract reusable auth guard decision logic and test router auth behavior against it
Co-Authored-By: Codex <codex@openai.com>
This commit is contained in:
@@ -5,6 +5,7 @@
|
||||
|
||||
import { describe, it, expect, beforeEach } from "vitest";
|
||||
import { decodeReturnTo } from "@/utils/returnToEncoding";
|
||||
import { evaluateAuthNavigation } from "@/router/authGuard";
|
||||
|
||||
describe("router beforeEach guard logic", () => {
|
||||
beforeEach(() => {
|
||||
@@ -17,38 +18,30 @@ describe("router beforeEach guard logic", () => {
|
||||
});
|
||||
});
|
||||
|
||||
// Simulate the guard logic from router/index.ts
|
||||
// Run the real auth guard decision logic from src/router/authGuard.ts
|
||||
async function runGuard(to, options = {}) {
|
||||
const { refreshSucceeds = true } = options;
|
||||
const hasLoginMarker = document.cookie
|
||||
.split(";")
|
||||
.some((c) => c.trim().startsWith("isLuciaLoggedIn="));
|
||||
const hasAccessToken = document.cookie
|
||||
.split(";")
|
||||
.some((c) => c.trim().startsWith("luciaToken="));
|
||||
const hasRefreshToken = document.cookie
|
||||
.split(";")
|
||||
.some((c) => c.trim().startsWith("luciaRefreshToken="));
|
||||
const isAuthenticated = hasLoginMarker && hasAccessToken;
|
||||
|
||||
if (to.name === "Login") {
|
||||
if (isAuthenticated) return { name: "Files" };
|
||||
}
|
||||
|
||||
const requiresAuth = (to.matched || []).some((r) => r.meta?.requiresAuth);
|
||||
if (requiresAuth && !isAuthenticated) {
|
||||
if (hasRefreshToken) {
|
||||
if (refreshSucceeds) return undefined;
|
||||
}
|
||||
return {
|
||||
path: "/login",
|
||||
query: {
|
||||
"return-to": btoa(to.fullPath || to.path || "/"),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
return undefined;
|
||||
return evaluateAuthNavigation(to, {
|
||||
getCookie: (name) => {
|
||||
const cookieArr = document.cookie.split(";");
|
||||
for (const cookie of cookieArr) {
|
||||
const c = cookie.trim();
|
||||
if (c.startsWith(`${name}=`)) {
|
||||
return c.slice(name.length + 1);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
},
|
||||
refreshSession: async () => {
|
||||
if (!refreshSucceeds) {
|
||||
throw new Error("refresh failed");
|
||||
}
|
||||
},
|
||||
setLoginMarker: () => {
|
||||
document.cookie = "isLuciaLoggedIn=true";
|
||||
},
|
||||
encodeReturnTo: (path) => btoa(path),
|
||||
});
|
||||
}
|
||||
|
||||
it("redirects logged-in user from Login to Files", () => {
|
||||
|
||||
Reference in New Issue
Block a user