v1.5: Alle Manager-Komponenten auf eigene API-Routen umgestellt

Neue interne Route Handler unter app/api/ (dishes inkl. Bulk-Delete,
sections, allergens, additives, menu-entries, dish-suggestions,
settings, admin/branding) ersetzen den direkten Browser→Postgrest-
Zugriff der bisherigen Supabase-Anbindung. Jede Route prüft Autorisierung
selbst (lib/auth/session.ts requireRole) statt sich auf Postgres-RLS zu
verlassen – ersetzt 1:1 die bisherigen Policies (öffentlich lesbar /
staff+admin schreiben / nur admin für Einstellungen & Benutzer).

Rezeptvorschlag-Dublettencheck (SuggestionForm) läuft jetzt zwingend
serverseitig im POST-Handler, da es keinen Browser→Postgres-Pfad mehr
gibt. "Passkey annehmen" (SuggestionReview) läuft transaktional
(Gericht anlegen + Vorschlag löschen in einem Schritt).

Logo/Favicon: neuer lokaler Dateispeicher (lib/branding.ts, Docker-
Volume) statt Supabase-Storage-Bucket, ausgeliefert über
app/branding/[filename]. logoUrl()/faviconUrl() liefern jetzt einfache
relative Pfade statt einer fest verdrahteten Supabase-Storage-URL.

DeepL-Route (api/translate) und Benutzerverwaltung (api/admin/users)
laufen jetzt gegen die users-Tabelle statt Supabase Auth.

Alle "use client"-Manager-Komponenten (DishManager, WeekEditor,
SectionManager, CodeListManager, SuggestionForm/Review, UserManager,
DesignEditor) rufen ihre jeweiligen /api/-Routen per fetch() statt den
Supabase-Browser-Client zu nutzen.
This commit is contained in:
2026-07-18 11:01:52 +02:00
parent 28c9ec15c8
commit a9a9cf7ba4
58 changed files with 1184 additions and 1858 deletions
+5 -14
View File
@@ -1,5 +1,5 @@
import { redirect } from "next/navigation";
import { createClient } from "@/lib/supabase/server";
import { getSession } from "@/lib/auth/session";
import AppHeader from "@/components/AppHeader";
export default async function AdminLayout({
@@ -7,24 +7,15 @@ export default async function AdminLayout({
}: {
children: React.ReactNode;
}) {
const supabase = await createClient();
const {
data: { user },
} = await supabase.auth.getUser();
if (!user) redirect("/login");
const { data: profile } = await supabase
.from("profiles")
.select("role, full_name")
.eq("id", user.id)
.single();
if (profile?.role !== "admin") redirect("/intern");
const session = await getSession();
if (!session) redirect("/login");
if (session.user.role !== "admin") redirect("/intern");
return (
<div className="flex-1 flex flex-col">
<AppHeader
role="admin"
displayName={profile.full_name || user.email || ""}
displayName={session.user.full_name || session.user.email}
/>
<main className="max-w-[1600px] mx-auto w-full px-4 py-6 flex-1">
{children}
+4 -2
View File
@@ -1,5 +1,7 @@
import { getSession } from "@/lib/auth/session";
import UserManager from "@/components/UserManager";
export default function AdminPage() {
return <UserManager />;
export default async function AdminPage() {
const session = await getSession();
return <UserManager meId={session?.user.id ?? ""} />;
}
+47
View File
@@ -0,0 +1,47 @@
import { NextResponse } from "next/server";
import { deleteCode, updateCode } from "@/lib/db/code-lists";
import { authErrorResponse, requireRole } from "@/lib/auth/session";
import { isSameOrigin } from "@/lib/origin";
export async function PATCH(
request: Request,
{ params }: { params: Promise<{ code: string }> }
) {
if (!isSameOrigin(request)) {
return NextResponse.json({ error: "Nicht erlaubt." }, { status: 403 });
}
try {
await requireRole(["staff", "admin"]);
const { code } = await params;
const body = await request.json();
const item = await updateCode("additives", code, body);
if (!item) return NextResponse.json({ error: "not_found" }, { status: 404 });
return NextResponse.json(item);
} catch (err) {
const res = authErrorResponse(err);
if (res) return res;
if (err instanceof Error && /duplicate key/i.test(err.message)) {
return NextResponse.json({ error: "duplicate_code" }, { status: 409 });
}
throw err;
}
}
export async function DELETE(
request: Request,
{ params }: { params: Promise<{ code: string }> }
) {
if (!isSameOrigin(request)) {
return NextResponse.json({ error: "Nicht erlaubt." }, { status: 403 });
}
try {
await requireRole(["staff", "admin"]);
const { code } = await params;
await deleteCode("additives", code);
return NextResponse.json({ ok: true });
} catch (err) {
const res = authErrorResponse(err);
if (res) return res;
throw err;
}
}
+27
View File
@@ -0,0 +1,27 @@
import { NextResponse } from "next/server";
import { createCode, listCodes } from "@/lib/db/code-lists";
import { authErrorResponse, requireRole } from "@/lib/auth/session";
import { isSameOrigin } from "@/lib/origin";
export async function GET() {
return NextResponse.json(await listCodes("additives"));
}
export async function POST(request: Request) {
if (!isSameOrigin(request)) {
return NextResponse.json({ error: "Nicht erlaubt." }, { status: 403 });
}
try {
await requireRole(["staff", "admin"]);
const body = await request.json();
const item = await createCode("additives", body);
return NextResponse.json(item, { status: 201 });
} catch (err) {
const res = authErrorResponse(err);
if (res) return res;
if (err instanceof Error && /duplicate key/i.test(err.message)) {
return NextResponse.json({ error: "duplicate_code" }, { status: 409 });
}
throw err;
}
}
+76
View File
@@ -0,0 +1,76 @@
import { NextResponse } from "next/server";
import { queryOne, query } from "@/lib/db";
import { removeBrandingFile, saveBrandingFile } from "@/lib/branding";
import { authErrorResponse, requireRole } from "@/lib/auth/session";
import { isSameOrigin } from "@/lib/origin";
type AssetKind = "logo" | "favicon";
const ASSET_COLUMN: Record<AssetKind, "logo_path" | "favicon_path"> = {
logo: "logo_path",
favicon: "favicon_path",
};
function isAssetKind(value: unknown): value is AssetKind {
return value === "logo" || value === "favicon";
}
export async function POST(request: Request) {
if (!isSameOrigin(request)) {
return NextResponse.json({ error: "Nicht erlaubt." }, { status: 403 });
}
try {
await requireRole(["admin"]);
const form = await request.formData();
const kind = form.get("kind");
const file = form.get("file");
if (!isAssetKind(kind) || !(file instanceof File)) {
return NextResponse.json({ error: "invalid_input" }, { status: 400 });
}
if (!file.type.startsWith("image/")) {
return NextResponse.json({ error: "invalid_image" }, { status: 400 });
}
const old = await queryOne<{ path: string | null }>(
`select ${ASSET_COLUMN[kind]} as path from settings where id = 1`
);
const ext = file.name.split(".").pop()?.toLowerCase() ?? "png";
const filename = `${kind}-${Date.now()}.${ext}`;
const buffer = Buffer.from(await file.arrayBuffer());
await saveBrandingFile(filename, buffer);
await query(`update settings set ${ASSET_COLUMN[kind]} = $1 where id = 1`, [filename]);
if (old?.path) await removeBrandingFile(old.path);
return NextResponse.json({ path: filename });
} catch (err) {
const res = authErrorResponse(err);
if (res) return res;
throw err;
}
}
export async function DELETE(request: Request) {
if (!isSameOrigin(request)) {
return NextResponse.json({ error: "Nicht erlaubt." }, { status: 403 });
}
try {
await requireRole(["admin"]);
const { kind } = (await request.json()) as { kind?: unknown };
if (!isAssetKind(kind)) {
return NextResponse.json({ error: "invalid_input" }, { status: 400 });
}
const old = await queryOne<{ path: string | null }>(
`select ${ASSET_COLUMN[kind]} as path from settings where id = 1`
);
await query(`update settings set ${ASSET_COLUMN[kind]} = null where id = 1`);
if (old?.path) await removeBrandingFile(old.path);
return NextResponse.json({ ok: true });
} catch (err) {
const res = authErrorResponse(err);
if (res) return res;
throw err;
}
}
+86 -52
View File
@@ -1,33 +1,48 @@
import { NextResponse } from "next/server";
import { createClient } from "@/lib/supabase/server";
import { createAdminClient } from "@/lib/supabase/admin";
import { query, queryOne } from "@/lib/db";
import { hashPassword } from "@/lib/auth/password";
import { requireRole, UnauthorizedError, ForbiddenError } from "@/lib/auth/session";
import { isSameOrigin } from "@/lib/origin";
import type { Profile } from "@/lib/types";
// Benutzerverwaltung (nur Admin). Läuft serverseitig mit dem
// Service-Role-Key, da das Anlegen/Löschen von Auth-Benutzern
// nicht über den anon key möglich ist.
// Benutzerverwaltung (nur Admin).
async function requireAdmin(request: Request) {
if (!isSameOrigin(request)) return null;
const supabase = await createClient();
const {
data: { user },
} = await supabase.auth.getUser();
if (!user) return null;
if (!isSameOrigin(request)) throw new ForbiddenError();
return requireRole(["admin"]);
}
const admin = createAdminClient();
const { data: profile } = await admin
.from("profiles")
.select("role")
.eq("id", user.id)
.single();
if (profile?.role !== "admin") return null;
return { user, admin };
function errorResponse(err: unknown) {
if (err instanceof UnauthorizedError || err instanceof ForbiddenError) {
return NextResponse.json({ error: "Nicht berechtigt." }, { status: 403 });
}
return null;
}
export async function GET(request: Request) {
try {
await requireAdmin(request);
} catch (err) {
const res = errorResponse(err);
if (res) return res;
throw err;
}
const profiles = await query<Profile>(
"select id, email, full_name, role, password_auth_enabled, created_at from users order by created_at"
);
return NextResponse.json(profiles);
}
export async function POST(request: Request) {
const ctx = await requireAdmin(request);
if (!ctx) return NextResponse.json({ error: "Nicht berechtigt." }, { status: 403 });
let session;
try {
session = await requireAdmin(request);
} catch (err) {
const res = errorResponse(err);
if (res) return res;
throw err;
}
void session;
const body = await request.json().catch(() => null);
const { email, password, full_name, role } = body ?? {};
@@ -41,28 +56,33 @@ export async function POST(request: Request) {
);
}
const { data, error } = await ctx.admin.auth.admin.createUser({
email,
password,
email_confirm: true,
user_metadata: { full_name: full_name ?? "", role },
});
if (error) {
return NextResponse.json(
{
error: /already been registered/i.test(error.message)
? "Diese E-Mail-Adresse ist bereits registriert."
: error.message,
},
{ status: 400 }
try {
const user = await queryOne<{ id: string }>(
`insert into users (email, password_hash, full_name, role)
values ($1, $2, $3, $4) returning id`,
[String(email).trim().toLowerCase(), hashPassword(password), full_name ?? "", role]
);
return NextResponse.json({ id: user?.id });
} catch (err) {
if (err instanceof Error && /unique/i.test(err.message)) {
return NextResponse.json(
{ error: "Diese E-Mail-Adresse ist bereits registriert." },
{ status: 400 }
);
}
throw err;
}
return NextResponse.json({ id: data.user?.id });
}
export async function PATCH(request: Request) {
const ctx = await requireAdmin(request);
if (!ctx) return NextResponse.json({ error: "Nicht berechtigt." }, { status: 403 });
let session;
try {
session = await requireAdmin(request);
} catch (err) {
const res = errorResponse(err);
if (res) return res;
throw err;
}
const body = await request.json().catch(() => null);
const { id, full_name, role, password } = body ?? {};
@@ -71,7 +91,7 @@ export async function PATCH(request: Request) {
}
// Der Admin darf sich nicht selbst die Admin-Rolle entziehen,
// sonst sperrt er sich aus der Verwaltung aus.
if (id === ctx.user.id && role === "staff") {
if (id === session.user.id && role === "staff") {
return NextResponse.json(
{ error: "Du kannst dir nicht selbst die Admin-Rolle entziehen." },
{ status: 400 }
@@ -85,35 +105,49 @@ export async function PATCH(request: Request) {
{ status: 400 }
);
}
const { error } = await ctx.admin.auth.admin.updateUserById(id, { password });
if (error) return NextResponse.json({ error: error.message }, { status: 400 });
await query("update users set password_hash = $1 where id = $2", [
hashPassword(password),
id,
]);
}
const updates: Record<string, string> = {};
if (typeof full_name === "string") updates.full_name = full_name;
if (role) updates.role = role;
if (Object.keys(updates).length > 0) {
const { error } = await ctx.admin.from("profiles").update(updates).eq("id", id);
if (error) return NextResponse.json({ error: error.message }, { status: 400 });
const fields: string[] = [];
const values: unknown[] = [];
if (typeof full_name === "string") {
values.push(full_name);
fields.push(`full_name = $${values.length}`);
}
if (role) {
values.push(role);
fields.push(`role = $${values.length}`);
}
if (fields.length > 0) {
values.push(id);
await query(`update users set ${fields.join(", ")} where id = $${values.length}`, values);
}
return NextResponse.json({ ok: true });
}
export async function DELETE(request: Request) {
const ctx = await requireAdmin(request);
if (!ctx) return NextResponse.json({ error: "Nicht berechtigt." }, { status: 403 });
let session;
try {
session = await requireAdmin(request);
} catch (err) {
const res = errorResponse(err);
if (res) return res;
throw err;
}
const body = await request.json().catch(() => null);
const { id } = body ?? {};
if (!id) return NextResponse.json({ error: "Ungültige Eingaben." }, { status: 400 });
if (id === ctx.user.id) {
if (id === session.user.id) {
return NextResponse.json(
{ error: "Du kannst dich nicht selbst löschen." },
{ status: 400 }
);
}
const { error } = await ctx.admin.auth.admin.deleteUser(id);
if (error) return NextResponse.json({ error: error.message }, { status: 400 });
await query("delete from users where id = $1", [id]);
return NextResponse.json({ ok: true });
}
+47
View File
@@ -0,0 +1,47 @@
import { NextResponse } from "next/server";
import { deleteCode, updateCode } from "@/lib/db/code-lists";
import { authErrorResponse, requireRole } from "@/lib/auth/session";
import { isSameOrigin } from "@/lib/origin";
export async function PATCH(
request: Request,
{ params }: { params: Promise<{ code: string }> }
) {
if (!isSameOrigin(request)) {
return NextResponse.json({ error: "Nicht erlaubt." }, { status: 403 });
}
try {
await requireRole(["staff", "admin"]);
const { code } = await params;
const body = await request.json();
const item = await updateCode("allergens", code, body);
if (!item) return NextResponse.json({ error: "not_found" }, { status: 404 });
return NextResponse.json(item);
} catch (err) {
const res = authErrorResponse(err);
if (res) return res;
if (err instanceof Error && /duplicate key/i.test(err.message)) {
return NextResponse.json({ error: "duplicate_code" }, { status: 409 });
}
throw err;
}
}
export async function DELETE(
request: Request,
{ params }: { params: Promise<{ code: string }> }
) {
if (!isSameOrigin(request)) {
return NextResponse.json({ error: "Nicht erlaubt." }, { status: 403 });
}
try {
await requireRole(["staff", "admin"]);
const { code } = await params;
await deleteCode("allergens", code);
return NextResponse.json({ ok: true });
} catch (err) {
const res = authErrorResponse(err);
if (res) return res;
throw err;
}
}
+27
View File
@@ -0,0 +1,27 @@
import { NextResponse } from "next/server";
import { createCode, listCodes } from "@/lib/db/code-lists";
import { authErrorResponse, requireRole } from "@/lib/auth/session";
import { isSameOrigin } from "@/lib/origin";
export async function GET() {
return NextResponse.json(await listCodes("allergens"));
}
export async function POST(request: Request) {
if (!isSameOrigin(request)) {
return NextResponse.json({ error: "Nicht erlaubt." }, { status: 403 });
}
try {
await requireRole(["staff", "admin"]);
const body = await request.json();
const item = await createCode("allergens", body);
return NextResponse.json(item, { status: 201 });
} catch (err) {
const res = authErrorResponse(err);
if (res) return res;
if (err instanceof Error && /duplicate key/i.test(err.message)) {
return NextResponse.json({ error: "duplicate_code" }, { status: 409 });
}
throw err;
}
}
@@ -0,0 +1,37 @@
import { NextResponse } from "next/server";
import { withTransaction } from "@/lib/db";
import { authErrorResponse, requireRole } from "@/lib/auth/session";
import { isSameOrigin } from "@/lib/origin";
export async function POST(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
if (!isSameOrigin(request)) {
return NextResponse.json({ error: "Nicht erlaubt." }, { status: 403 });
}
try {
await requireRole(["staff", "admin"]);
const { id } = await params;
const created = await withTransaction(async (client) => {
const suggestion = await client.query<{ name: string }>(
"select name from dish_suggestions where id = $1",
[id]
);
if (suggestion.rows.length === 0) return null;
await client.query("insert into dishes (name, price) values ($1, 0)", [
suggestion.rows[0].name,
]);
await client.query("delete from dish_suggestions where id = $1", [id]);
return true;
});
if (!created) return NextResponse.json({ error: "not_found" }, { status: 404 });
return NextResponse.json({ ok: true });
} catch (err) {
const res = authErrorResponse(err);
if (res) return res;
throw err;
}
}
+23
View File
@@ -0,0 +1,23 @@
import { NextResponse } from "next/server";
import { query } from "@/lib/db";
import { authErrorResponse, requireRole } from "@/lib/auth/session";
import { isSameOrigin } from "@/lib/origin";
export async function DELETE(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
if (!isSameOrigin(request)) {
return NextResponse.json({ error: "Nicht erlaubt." }, { status: 403 });
}
try {
await requireRole(["staff", "admin"]);
const { id } = await params;
await query("delete from dish_suggestions where id = $1", [id]);
return NextResponse.json({ ok: true });
} catch (err) {
const res = authErrorResponse(err);
if (res) return res;
throw err;
}
}
+45
View File
@@ -0,0 +1,45 @@
import { NextResponse } from "next/server";
import { query, queryOne } from "@/lib/db";
import { authErrorResponse, requireRole } from "@/lib/auth/session";
import { isSameOrigin } from "@/lib/origin";
import type { DishSuggestion } from "@/lib/types";
export async function GET() {
try {
await requireRole(["staff", "admin"]);
} catch (err) {
const res = authErrorResponse(err);
if (res) return res;
throw err;
}
const items = await query<DishSuggestion>(
"select * from dish_suggestions order by created_at desc"
);
return NextResponse.json(items);
}
export async function POST(request: Request) {
if (!isSameOrigin(request)) {
return NextResponse.json({ error: "Nicht erlaubt." }, { status: 403 });
}
const body = (await request.json().catch(() => ({}))) as {
name?: string;
description?: string;
};
const name = body.name?.trim();
if (!name) return NextResponse.json({ error: "name_required" }, { status: 400 });
// Serverseitig statt clientseitig (wie zuvor über den anon-Postgrest-
// Zugriff): es gibt keinen Browser→Postgres-Pfad mehr.
const existing = await queryOne<{ id: string }>(
"select id from dishes where name ilike $1 limit 1",
[name]
);
if (existing) return NextResponse.json({ error: "duplicate" }, { status: 409 });
await query("insert into dish_suggestions (name, description) values ($1, $2)", [
name,
body.description?.trim() || null,
]);
return NextResponse.json({ ok: true }, { status: 201 });
}
+57
View File
@@ -0,0 +1,57 @@
import { NextResponse } from "next/server";
import { query, queryOne } from "@/lib/db";
import { authErrorResponse, requireRole } from "@/lib/auth/session";
import { isSameOrigin } from "@/lib/origin";
import type { Dish } from "@/lib/types";
export async function PATCH(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
if (!isSameOrigin(request)) {
return NextResponse.json({ error: "Nicht erlaubt." }, { status: 403 });
}
try {
await requireRole(["staff", "admin"]);
const { id } = await params;
const body = (await request.json()) as {
name: string;
name_en: string | null;
name_pl: string | null;
price: number;
allergens: string[];
additives: string[];
};
const dish = await queryOne<Dish>(
`update dishes set name = $1, name_en = $2, name_pl = $3, price = $4,
allergens = $5, additives = $6
where id = $7 returning *`,
[body.name, body.name_en, body.name_pl, body.price, body.allergens, body.additives, id]
);
if (!dish) return NextResponse.json({ error: "not_found" }, { status: 404 });
return NextResponse.json(dish);
} catch (err) {
const res = authErrorResponse(err);
if (res) return res;
throw err;
}
}
export async function DELETE(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
if (!isSameOrigin(request)) {
return NextResponse.json({ error: "Nicht erlaubt." }, { status: 403 });
}
try {
await requireRole(["staff", "admin"]);
const { id } = await params;
await query("delete from dishes where id = $1", [id]);
return NextResponse.json({ ok: true });
} catch (err) {
const res = authErrorResponse(err);
if (res) return res;
throw err;
}
}
+23
View File
@@ -0,0 +1,23 @@
import { NextResponse } from "next/server";
import { query } from "@/lib/db";
import { authErrorResponse, requireRole } from "@/lib/auth/session";
import { isSameOrigin } from "@/lib/origin";
export async function POST(request: Request) {
if (!isSameOrigin(request)) {
return NextResponse.json({ error: "Nicht erlaubt." }, { status: 403 });
}
try {
await requireRole(["staff", "admin"]);
const { ids } = (await request.json()) as { ids: string[] };
if (!Array.isArray(ids) || ids.length === 0) {
return NextResponse.json({ error: "invalid_input" }, { status: 400 });
}
await query("delete from dishes where id = any($1::uuid[])", [ids]);
return NextResponse.json({ ok: true });
} catch (err) {
const res = authErrorResponse(err);
if (res) return res;
throw err;
}
}
+37
View File
@@ -0,0 +1,37 @@
import { NextResponse } from "next/server";
import { query, queryOne } from "@/lib/db";
import { authErrorResponse, requireRole } from "@/lib/auth/session";
import { isSameOrigin } from "@/lib/origin";
import type { Dish } from "@/lib/types";
export async function GET() {
const dishes = await query<Dish>("select * from dishes order by name");
return NextResponse.json(dishes);
}
export async function POST(request: Request) {
if (!isSameOrigin(request)) {
return NextResponse.json({ error: "Nicht erlaubt." }, { status: 403 });
}
try {
await requireRole(["staff", "admin"]);
const body = (await request.json()) as {
name: string;
name_en: string | null;
name_pl: string | null;
price: number;
allergens: string[];
additives: string[];
};
const dish = await queryOne<Dish>(
`insert into dishes (name, name_en, name_pl, price, allergens, additives)
values ($1, $2, $3, $4, $5, $6) returning *`,
[body.name, body.name_en, body.name_pl, body.price, body.allergens, body.additives]
);
return NextResponse.json(dish, { status: 201 });
} catch (err) {
const res = authErrorResponse(err);
if (res) return res;
throw err;
}
}
+23
View File
@@ -0,0 +1,23 @@
import { NextResponse } from "next/server";
import { query } from "@/lib/db";
import { authErrorResponse, requireRole } from "@/lib/auth/session";
import { isSameOrigin } from "@/lib/origin";
export async function DELETE(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
if (!isSameOrigin(request)) {
return NextResponse.json({ error: "Nicht erlaubt." }, { status: 403 });
}
try {
await requireRole(["staff", "admin"]);
const { id } = await params;
await query("delete from menu_entries where id = $1", [id]);
return NextResponse.json({ ok: true });
} catch (err) {
const res = authErrorResponse(err);
if (res) return res;
throw err;
}
}
+41
View File
@@ -0,0 +1,41 @@
import { NextResponse } from "next/server";
import { queryOne } from "@/lib/db";
import { loadMenuEntries } from "@/lib/db/menu-entries";
import { authErrorResponse, requireRole } from "@/lib/auth/session";
import { isSameOrigin } from "@/lib/origin";
export async function GET(request: Request) {
const { searchParams } = new URL(request.url);
const from = searchParams.get("from");
const to = searchParams.get("to");
if (!from || !to) {
return NextResponse.json({ error: "invalid_input" }, { status: 400 });
}
return NextResponse.json(await loadMenuEntries(from, to));
}
export async function POST(request: Request) {
if (!isSameOrigin(request)) {
return NextResponse.json({ error: "Nicht erlaubt." }, { status: 403 });
}
try {
await requireRole(["staff", "admin"]);
const body = (await request.json()) as {
menu_date: string;
section_key: string;
dish_id: string;
};
const entry = await queryOne<{ id: string }>(
"insert into menu_entries (menu_date, section_key, dish_id) values ($1, $2, $3) returning id",
[body.menu_date, body.section_key, body.dish_id]
);
return NextResponse.json(entry, { status: 201 });
} catch (err) {
const res = authErrorResponse(err);
if (res) return res;
if (err instanceof Error && /duplicate key/i.test(err.message)) {
return NextResponse.json({ error: "duplicate_entry" }, { status: 409 });
}
throw err;
}
}
+62
View File
@@ -0,0 +1,62 @@
import { NextResponse } from "next/server";
import { query, queryOne } from "@/lib/db";
import { authErrorResponse, requireRole } from "@/lib/auth/session";
import { isSameOrigin } from "@/lib/origin";
import type { Section } from "@/lib/types";
export async function PATCH(
request: Request,
{ params }: { params: Promise<{ key: string }> }
) {
if (!isSameOrigin(request)) {
return NextResponse.json({ error: "Nicht erlaubt." }, { status: 403 });
}
try {
await requireRole(["staff", "admin"]);
const { key } = await params;
const body = (await request.json()) as Partial<
Pick<Section, "label" | "label_en" | "label_pl" | "time_range" | "sort">
>;
const fields: string[] = [];
const values: unknown[] = [];
for (const col of ["label", "label_en", "label_pl", "time_range", "sort"] as const) {
if (body[col] !== undefined) {
values.push(body[col]);
fields.push(`${col} = $${values.length}`);
}
}
if (fields.length === 0) return NextResponse.json({ error: "empty_update" }, { status: 400 });
values.push(key);
const section = await queryOne<Section>(
`update sections set ${fields.join(", ")} where key = $${values.length} returning *`,
values
);
if (!section) return NextResponse.json({ error: "not_found" }, { status: 404 });
return NextResponse.json(section);
} catch (err) {
const res = authErrorResponse(err);
if (res) return res;
throw err;
}
}
export async function DELETE(
request: Request,
{ params }: { params: Promise<{ key: string }> }
) {
if (!isSameOrigin(request)) {
return NextResponse.json({ error: "Nicht erlaubt." }, { status: 403 });
}
try {
await requireRole(["staff", "admin"]);
const { key } = await params;
await query("delete from sections where key = $1", [key]);
return NextResponse.json({ ok: true });
} catch (err) {
const res = authErrorResponse(err);
if (res) return res;
throw err;
}
}
+39
View File
@@ -0,0 +1,39 @@
import { NextResponse } from "next/server";
import { query, queryOne } from "@/lib/db";
import { authErrorResponse, requireRole } from "@/lib/auth/session";
import { isSameOrigin } from "@/lib/origin";
import type { Section } from "@/lib/types";
export async function GET() {
const sections = await query<Section>("select * from sections order by sort");
return NextResponse.json(sections);
}
export async function POST(request: Request) {
if (!isSameOrigin(request)) {
return NextResponse.json({ error: "Nicht erlaubt." }, { status: 403 });
}
try {
await requireRole(["staff", "admin"]);
const body = (await request.json()) as {
label: string;
label_en: string | null;
label_pl: string | null;
time_range: string;
};
const maxRow = await queryOne<{ sort: number }>(
"select sort from sections order by sort desc limit 1"
);
const section = await queryOne<Section>(
`insert into sections (label, label_en, label_pl, time_range, sort)
values ($1, $2, $3, $4, $5) returning *`,
[body.label, body.label_en, body.label_pl, body.time_range, (maxRow?.sort ?? 0) + 1]
);
return NextResponse.json(section, { status: 201 });
} catch (err) {
const res = authErrorResponse(err);
if (res) return res;
throw err;
}
}
+25
View File
@@ -0,0 +1,25 @@
import { NextResponse } from "next/server";
import { query } from "@/lib/db";
import { getSettings } from "@/lib/db/settings";
import { authErrorResponse, requireRole } from "@/lib/auth/session";
import { isSameOrigin } from "@/lib/origin";
export async function GET() {
return NextResponse.json(await getSettings());
}
export async function PATCH(request: Request) {
if (!isSameOrigin(request)) {
return NextResponse.json({ error: "Nicht erlaubt." }, { status: 403 });
}
try {
await requireRole(["admin"]);
const { colors } = (await request.json()) as { colors: Record<string, string> };
await query("update settings set colors = $1 where id = 1", [JSON.stringify(colors)]);
return NextResponse.json({ ok: true });
} catch (err) {
const res = authErrorResponse(err);
if (res) return res;
throw err;
}
}
+20 -21
View File
@@ -1,6 +1,6 @@
import { NextResponse } from "next/server";
import { createClient } from "@/lib/supabase/server";
import { createAdminClient } from "@/lib/supabase/admin";
import { query } from "@/lib/db";
import { requireRole, UnauthorizedError, ForbiddenError } from "@/lib/auth/session";
import { isSameOrigin } from "@/lib/origin";
// Übersetzt einen deutschen Text nach Englisch/Polnisch via DeepL und
@@ -43,20 +43,16 @@ export async function POST(request: Request) {
return NextResponse.json({ error: "Nicht erlaubt." }, { status: 403 });
}
const supabase = await createClient();
const {
data: { user },
} = await supabase.auth.getUser();
if (!user) return NextResponse.json({ error: "Nicht angemeldet." }, { status: 401 });
const admin = createAdminClient();
const { data: profile } = await admin
.from("profiles")
.select("role")
.eq("id", user.id)
.single();
if (!profile || !["staff", "admin"].includes(profile.role)) {
return NextResponse.json({ error: "Nicht berechtigt." }, { status: 403 });
try {
await requireRole(["staff", "admin"]);
} catch (err) {
if (err instanceof UnauthorizedError) {
return NextResponse.json({ error: "Nicht angemeldet." }, { status: 401 });
}
if (err instanceof ForbiddenError) {
return NextResponse.json({ error: "Nicht berechtigt." }, { status: 403 });
}
throw err;
}
const body = await request.json().catch(() => null);
@@ -83,11 +79,14 @@ export async function POST(request: Request) {
if (!en || !pl) throw new Error("Keine Übersetzung erhalten.");
if (persist) {
const { error } = await admin
.from(table)
.update({ [`${config.textColumn}_en`]: en, [`${config.textColumn}_pl`]: pl })
.eq(config.idColumn, id);
if (error) throw new Error(error.message);
// table/idColumn/textColumn kommen ausschließlich aus dem oben
// geprüften ALLOWED_TABLES-Whitelist, nie aus Nutzereingaben –
// sicher für die String-Interpolation in der Query.
await query(
`update ${table} set ${config.textColumn}_en = $1, ${config.textColumn}_pl = $2
where ${config.idColumn} = $3`,
[en, pl, id]
);
}
return NextResponse.json({ configured: true, en, pl });
+32
View File
@@ -0,0 +1,32 @@
import { readBrandingFile } from "@/lib/branding";
const CONTENT_TYPES: Record<string, string> = {
png: "image/png",
jpg: "image/jpeg",
jpeg: "image/jpeg",
webp: "image/webp",
svg: "image/svg+xml",
ico: "image/x-icon",
gif: "image/gif",
};
export async function GET(
request: Request,
{ params }: { params: Promise<{ filename: string }> }
) {
const { filename } = await params;
const data = await readBrandingFile(filename);
if (!data) return new Response("Not found", { status: 404 });
const ext = filename.split(".").pop()?.toLowerCase() ?? "";
const contentType = CONTENT_TYPES[ext] ?? "application/octet-stream";
return new Response(new Uint8Array(data), {
headers: {
"Content-Type": contentType,
// Dateinamen tragen bereits einen Date.now()-Suffix, ein neuer
// Upload bekommt also automatisch einen neuen Namen.
"Cache-Control": "public, max-age=31536000, immutable",
},
});
}
+1 -1
View File
@@ -1,7 +1,7 @@
@import "tailwindcss";
/* Farb-Variablen: Defaults entsprechen r-hofmann.de; werden zur Laufzeit
aus den Einstellungen (Supabase settings.colors) überschrieben. */
aus den Einstellungen (settings.colors) überschrieben. */
:root {
--c-primary: #003388;
--c-primary-dark: #0d315c;
+5 -15
View File
@@ -1,5 +1,5 @@
import { redirect } from "next/navigation";
import { createClient } from "@/lib/supabase/server";
import { getSession } from "@/lib/auth/session";
import AppHeader from "@/components/AppHeader";
export default async function InternLayout({
@@ -7,24 +7,14 @@ export default async function InternLayout({
}: {
children: React.ReactNode;
}) {
const supabase = await createClient();
const {
data: { user },
} = await supabase.auth.getUser();
if (!user) redirect("/login");
const { data: profile } = await supabase
.from("profiles")
.select("role, full_name")
.eq("id", user.id)
.single();
if (!profile || !["staff", "admin"].includes(profile.role)) redirect("/");
const session = await getSession();
if (!session) redirect("/login");
return (
<div className="flex-1 flex flex-col">
<AppHeader
role={profile.role}
displayName={profile.full_name || user.email || ""}
role={session.user.role}
displayName={session.user.full_name || session.user.email}
/>
<main className="max-w-[1600px] mx-auto w-full px-4 py-6 flex-1">
{children}
+9 -19
View File
@@ -1,34 +1,24 @@
import { redirect } from "next/navigation";
import { createClient } from "@/lib/supabase/server";
import { getSession } from "@/lib/auth/session";
import AppHeader from "@/components/AppHeader";
import AccountManager from "@/components/AccountManager";
export default async function KontoPage() {
const supabase = await createClient();
const {
data: { user },
} = await supabase.auth.getUser();
if (!user) redirect("/login");
const { data: profile } = await supabase
.from("profiles")
.select("role, full_name, password_auth_enabled")
.eq("id", user.id)
.single();
if (!profile || !["staff", "admin"].includes(profile.role)) redirect("/");
const session = await getSession();
if (!session) redirect("/login");
return (
<div className="flex-1 flex flex-col">
<AppHeader
role={profile.role}
displayName={profile.full_name || user.email || ""}
role={session.user.role}
displayName={session.user.full_name || session.user.email}
/>
<main className="max-w-[1600px] mx-auto w-full px-4 py-6 flex-1">
<AccountManager
role={profile.role}
initialFullName={profile.full_name ?? ""}
initialEmail={user.email ?? ""}
initialPasswordAuthEnabled={profile.password_auth_enabled}
role={session.user.role}
initialFullName={session.user.full_name}
initialEmail={session.user.email}
initialPasswordAuthEnabled={session.user.password_auth_enabled}
/>
</main>
</div>
+4 -13
View File
@@ -1,7 +1,7 @@
import type { Metadata } from "next";
import { Geist } from "next/font/google";
import "./globals.css";
import { createClient } from "@/lib/supabase/server";
import { getSettings } from "@/lib/db/settings";
import { COLOR_VARS, DEFAULT_COLORS, faviconUrl, SITE_TITLE } from "@/lib/types";
import { getDictionary, getLocale } from "@/lib/i18n";
import { LocaleProvider } from "@/components/i18n/LocaleProvider";
@@ -16,12 +16,7 @@ const geistSans = Geist({
});
export async function generateMetadata(): Promise<Metadata> {
const supabase = await createClient();
const { data: settings } = await supabase
.from("settings")
.select("favicon_path")
.eq("id", 1)
.maybeSingle();
const settings = await getSettings();
return {
title: SITE_TITLE,
@@ -38,16 +33,12 @@ export default async function RootLayout({
}: Readonly<{
children: React.ReactNode;
}>) {
const supabase = await createClient();
const [{ data: settings }, locale] = await Promise.all([
supabase.from("settings").select("colors").eq("id", 1).maybeSingle(),
getLocale(),
]);
const [settings, locale] = await Promise.all([getSettings(), getLocale()]);
const dict = getDictionary(locale);
const colors: Record<string, string> = {
...DEFAULT_COLORS,
...((settings?.colors as Record<string, string>) ?? {}),
...(settings?.colors ?? {}),
};
const style = Object.fromEntries(
Object.entries(COLOR_VARS).map(([key, cssVar]) => [cssVar, colors[key]])
+12 -24
View File
@@ -1,5 +1,7 @@
import Link from "next/link";
import { createClient } from "@/lib/supabase/server";
import { query } from "@/lib/db";
import { loadMenuEntries } from "@/lib/db/menu-entries";
import { getSettings } from "@/lib/db/settings";
import {
addDays,
dishCodes,
@@ -11,7 +13,7 @@ import {
} from "@/lib/menu";
import { getDictionary, getLocale } from "@/lib/i18n";
import { localized, logoUrl, SITE_TITLE } from "@/lib/types";
import type { CodeItem, MenuEntry, Section } from "@/lib/types";
import type { CodeItem, Section } from "@/lib/types";
import PublicMobileMenu from "@/components/PublicMobileMenu";
import LanguageSwitcher from "@/components/i18n/LanguageSwitcher";
@@ -31,29 +33,15 @@ export default async function Home({
iso: addDays(monday, i),
}));
const supabase = await createClient();
const [sectionsRes, entriesRes, allergensRes, additivesRes, settingsRes] =
await Promise.all([
supabase.from("sections").select("*").order("sort"),
supabase
.from("menu_entries")
.select(
"id, menu_date, section_key, position, dish:dishes(id, name, name_en, name_pl, price, allergens, additives)"
)
.gte("menu_date", monday)
.lte("menu_date", friday)
.order("position")
.order("created_at"),
supabase.from("allergens").select("*").order("sort"),
supabase.from("additives").select("*").order("sort"),
supabase.from("settings").select("logo_path").eq("id", 1).maybeSingle(),
]);
const [sections, entries, allergens, additives, settings] = await Promise.all([
query<Section>("select * from sections order by sort"),
loadMenuEntries(monday, friday),
query<CodeItem>("select * from allergens order by sort"),
query<CodeItem>("select * from additives order by sort"),
getSettings(),
]);
const sections = (sectionsRes.data ?? []) as Section[];
const entries = (entriesRes.data ?? []) as unknown as MenuEntry[];
const allergens = (allergensRes.data ?? []) as CodeItem[];
const additives = (additivesRes.data ?? []) as CodeItem[];
const logo = logoUrl(settingsRes.data?.logo_path);
const logo = logoUrl(settings?.logo_path);
return (
<div className="flex-1 px-4 py-6 max-w-[1600px] mx-auto w-full">