fix: redirect expired portal sessions

This commit is contained in:
Leon Tonhäuser committed 2026-08-11 17:13:44 +02:00
1 parent b1ef4a8186
commit 1279f46b1f
4 files changed
+69 -4

No files matched your search

+42
View File
@@ -0,0 +1,42 @@
import { afterEach, expect, test, vi } from "vitest";
const { redirect } = vi.hoisted(() => ({
redirect: vi.fn((destination: string): never => {
throw new Error(`NEXT_REDIRECT:${destination}`);
}),
}));
vi.mock("next/navigation", () => ({ redirect }));
import { PrincipalAuthorizationError } from "./principal";
import { requirePageAccess } from "./page-access";
afterEach(() => vi.clearAllMocks());
test("redirects an expired protected-page session to sign-in", async () => {
const expired = new PrincipalAuthorizationError("AUTHENTICATION_REQUIRED");
await expect(
requirePageAccess(async () => {
throw expired;
}),
).rejects.toThrow("NEXT_REDIRECT:/anmelden");
});
test("rethrows non-session failures unchanged", async () => {
const unavailable = new Error("database unavailable");
await expect(
requirePageAccess(async () => {
throw unavailable;
}),
).rejects.toBe(unavailable);
expect(redirect).not.toHaveBeenCalled();
});
test("returns the principal when the page guard succeeds", async () => {
const principal = { userId: "admin-1" };
await expect(requirePageAccess(async () => principal)).resolves.toBe(principal);
expect(redirect).not.toHaveBeenCalled();
});
+21
View File
@@ -0,0 +1,21 @@
import "server-only";
import { redirect } from "next/navigation";
import { PrincipalAuthorizationError } from "@/modules/auth/principal";
export async function requirePageAccess<T>(
loadPrincipal: () => Promise<T>,
): Promise<T> {
try {
return await loadPrincipal();
} catch (error) {
if (
error instanceof PrincipalAuthorizationError &&
error.code === "AUTHENTICATION_REQUIRED"
) {
redirect("/anmelden");
}
throw error;
}
}