fix: centralize protected page access

This commit is contained in:
Leon Tonhäuser committed 2026-08-11 17:31:23 +02:00
1 parent 844b8f7afd
commit e328267763
11 files changed
+132 -25

No files matched your search

+50
View File
@@ -0,0 +1,50 @@
import { beforeEach, expect, test, vi } from "vitest";
const mocks = vi.hoisted(() => {
class PrincipalAuthorizationError extends Error {
constructor(readonly code: string) {
super(code);
}
}
return {
PrincipalAuthorizationError,
headers: vi.fn(),
redirect: vi.fn((destination: string): never => {
throw new Error(`NEXT_REDIRECT:${destination}`);
}),
requireAdmin: vi.fn(),
};
});
vi.mock("react", () => ({ cache: (callback: unknown) => callback }));
vi.mock("next/headers", () => ({ headers: mocks.headers }));
vi.mock("next/navigation", () => ({ redirect: mocks.redirect }));
vi.mock("@/modules/auth/principal", () => ({
PrincipalAuthorizationError: mocks.PrincipalAuthorizationError,
requireAdmin: mocks.requireAdmin,
}));
import { PrincipalAuthorizationError } from "@/modules/auth/principal";
import { requireAdminPage } from "./access";
beforeEach(() => {
vi.clearAllMocks();
mocks.headers.mockResolvedValue(new Headers());
});
test("redirects an expired admin page loader session to sign-in", async () => {
mocks.requireAdmin.mockRejectedValue(
new PrincipalAuthorizationError("AUTHENTICATION_REQUIRED"),
);
await expect(requireAdminPage()).rejects.toThrow("NEXT_REDIRECT:/anmelden");
});
test("rethrows non-session admin page loader failures unchanged", async () => {
const unavailable = new Error("database unavailable");
mocks.requireAdmin.mockRejectedValue(unavailable);
await expect(requireAdminPage()).rejects.toBe(unavailable);
});
+12
View File
@@ -0,0 +1,12 @@
import "server-only";
import { cache } from "react";
import { headers } from "next/headers";
import { requirePageAccess } from "@/modules/auth/page-access";
import { requireAdmin } from "@/modules/auth/principal";
export const requireAdminPage = cache(async () =>
requirePageAccess(async () => requireAdmin(new Headers(await headers()))),
);
+4 -4
View File
@@ -1,9 +1,9 @@
import Link from "next/link";
import { headers } from "next/headers";
import { requireAdmin } from "@/modules/auth/principal";
import { listAuditEvents, type AuditEventRow } from "@/modules/audit/queries";
import { requireAdminPage } from "../access";
const berlinFormatter = new Intl.DateTimeFormat("de-DE", {
timeZone: "Europe/Berlin",
dateStyle: "short",
@@ -13,7 +13,7 @@ const berlinFormatter = new Intl.DateTimeFormat("de-DE", {
type SearchParams = Promise<Record<string, string | string[] | undefined>>;
export default async function AuditPage({ searchParams }: { searchParams: SearchParams }) {
await requireAdmin(new Headers(await headers()));
await requireAdminPage();
const params = await searchParams;
const eventType = firstParam(params, "eventType");
@@ -156,4 +156,4 @@ function buildPaginationHref(params: {
if (params.dateTo) searchParams.set("dateTo", params.dateTo);
searchParams.set("cursor", params.cursor);
return searchParams.toString();
}
}
+3 -5
View File
@@ -1,13 +1,11 @@
import type { ReactNode } from "react";
import { headers } from "next/headers";
import { PortalShell } from "@/components/layout/portal-shell";
import { requirePageAccess } from "@/modules/auth/page-access";
import { requireAdmin } from "@/modules/auth/principal";
import { requireAdminPage } from "./access";
export default async function AdminLayout({ children }: Readonly<{ children: ReactNode }>) {
await requirePageAccess(async () => requireAdmin(new Headers(await headers())));
await requireAdminPage();
return (
<PortalShell
+3 -4
View File
@@ -1,16 +1,15 @@
import { eq, sql, and, desc, gte } from "drizzle-orm";
import { db } from "@/db/client";
import { usages, editorialAccounts } from "@/db/schema";
import { requireAdmin } from "@/modules/auth/principal";
import { headers } from "next/headers";
import Link from "next/link";
import { PageHeader } from "@/components/ui/page-header";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { requireAdminPage } from "./access";
import { DownloadsChart } from "./downloads-chart-lazy";
export default async function AdminDashboardPage() {
await requireAdmin(new Headers(await headers()));
await requireAdminPage();
const now = new Date();
const firstDayOfMonth = new Date(Date.UTC(now.getFullYear(), now.getMonth(), 1));
@@ -196,4 +195,4 @@ export default async function AdminDashboardPage() {
</div>
</div>
);
}
}
@@ -1,9 +1,7 @@
import Link from "next/link";
import { Plus, Play, Trash2, ArrowLeft } from "lucide-react";
import { notFound } from "next/navigation";
import { headers } from "next/headers";
import { requireAdmin } from "@/modules/auth/principal";
import { autoRuleService } from "@/modules/albums/auto-rules";
import { db } from "@/db/client";
import { editorialAccounts } from "@/db/schema";
@@ -14,6 +12,7 @@ import { Input } from "@/components/ui/input";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { PageHeader } from "@/components/ui/page-header";
import { requireAdminPage } from "../../../access";
import { applyAutoRulesAction, createAutoRuleAction, deleteAutoRuleAction } from "./actions";
type AutoRulesPageProps = Readonly<{
@@ -21,7 +20,7 @@ type AutoRulesPageProps = Readonly<{
}>;
export default async function AutoRulesPage({ params }: AutoRulesPageProps) {
await requireAdmin(new Headers(await headers()));
await requireAdminPage();
const { id } = await params;
const [editorial] = await db
+3 -3
View File
@@ -1,15 +1,15 @@
import { eq, desc, and, sql, inArray } from "drizzle-orm";
import { db } from "@/db/client";
import { billingReports, usages, editorialAccounts } from "@/db/schema";
import { requireActiveEditorial } from "@/modules/auth/principal";
import { headers } from "next/headers";
import Link from "next/link";
import { formatBerlinDateTime } from "@/modules/downloads/format";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { FileText } from "lucide-react";
import { requireEditorial } from "../access";
export default async function AbrechnungenPage() {
const principal = await requireActiveEditorial(new Headers(await headers()));
const principal = await requireEditorial();
// 1. Hole alle PDF-Abrechnungen (abgeschlossene Reports)
const reports = await db
+50
View File
@@ -0,0 +1,50 @@
import { beforeEach, expect, test, vi } from "vitest";
const mocks = vi.hoisted(() => {
class PrincipalAuthorizationError extends Error {
constructor(readonly code: string) {
super(code);
}
}
return {
PrincipalAuthorizationError,
headers: vi.fn(),
redirect: vi.fn((destination: string): never => {
throw new Error(`NEXT_REDIRECT:${destination}`);
}),
requireActiveEditorial: vi.fn(),
};
});
vi.mock("react", () => ({ cache: (callback: unknown) => callback }));
vi.mock("next/headers", () => ({ headers: mocks.headers }));
vi.mock("next/navigation", () => ({ redirect: mocks.redirect }));
vi.mock("@/modules/auth/principal", () => ({
PrincipalAuthorizationError: mocks.PrincipalAuthorizationError,
requireActiveEditorial: mocks.requireActiveEditorial,
}));
import { PrincipalAuthorizationError } from "@/modules/auth/principal";
import { requireEditorial } from "./access";
beforeEach(() => {
vi.clearAllMocks();
mocks.headers.mockResolvedValue(new Headers());
});
test("redirects an expired editorial page loader session to sign-in", async () => {
mocks.requireActiveEditorial.mockRejectedValue(
new PrincipalAuthorizationError("AUTHENTICATION_REQUIRED"),
);
await expect(requireEditorial()).rejects.toThrow("NEXT_REDIRECT:/anmelden");
});
test("rethrows non-session editorial page loader failures unchanged", async () => {
const unavailable = new Error("database unavailable");
mocks.requireActiveEditorial.mockRejectedValue(unavailable);
await expect(requireEditorial()).rejects.toBe(unavailable);
});
+2 -1
View File
@@ -4,8 +4,9 @@ import { cache } from "react";
import { headers } from "next/headers";
import { requirePageAccess } from "@/modules/auth/page-access";
import { requireActiveEditorial } from "@/modules/auth/principal";
export const requireEditorial = cache(async () =>
requireActiveEditorial(new Headers(await headers())),
requirePageAccess(async () => requireActiveEditorial(new Headers(await headers()))),
);
+1 -2
View File
@@ -1,12 +1,11 @@
import type { ReactNode } from "react";
import { PortalShell } from "@/components/layout/portal-shell";
import { requirePageAccess } from "@/modules/auth/page-access";
import { requireEditorial } from "./access";
export default async function EditorialLayout({ children }: Readonly<{ children: ReactNode }>) {
await requirePageAccess(requireEditorial);
await requireEditorial();
return (
<PortalShell
+2 -3
View File
@@ -1,16 +1,15 @@
/* eslint-disable @next/next/no-img-element */
import { headers } from "next/headers";
import { PageHeader } from "@/components/ui/page-header";
import { requireActiveEditorial } from "@/modules/auth/principal";
import { lightboxService } from "@/modules/lightbox/service";
import { immichClient } from "@/modules/immich/client";
import Link from "next/link";
import { RemoveLightboxItemButton } from "./RemoveLightboxItemButton";
import { DownloadLightboxForm } from "./DownloadLightboxForm";
import { requireEditorial } from "../access";
export default async function LightboxPage() {
const principal = await requireActiveEditorial(new Headers(await headers()));
const principal = await requireEditorial();
const items = await lightboxService.getLightboxItems(principal.editorialId);
// Fetch asset details for all items in the lightbox