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:
@@ -107,4 +107,25 @@ export async function destroySession(): Promise<void> {
|
||||
store.delete(SESSION_COOKIE);
|
||||
}
|
||||
|
||||
/** Wandelt UnauthorizedError/ForbiddenError in die passende JSON-Antwort
|
||||
* um; gibt null zurück, wenn err ein anderer Fehler ist (dann soll der
|
||||
* Aufrufer ihn weiterwerfen). Reduziert Wiederholung des immer gleichen
|
||||
* try/catch-Musters in den Route-Handlern. */
|
||||
export function authErrorResponse(err: unknown): Response | null {
|
||||
if (err instanceof UnauthorizedError) {
|
||||
return NextResponseJson({ error: "unauthorized" }, 401);
|
||||
}
|
||||
if (err instanceof ForbiddenError) {
|
||||
return NextResponseJson({ error: "forbidden" }, 403);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function NextResponseJson(body: unknown, status: number): Response {
|
||||
return new Response(JSON.stringify(body), {
|
||||
status,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
}
|
||||
|
||||
export { REFRESH_THRESHOLD_MS, hashToken, isSecureCookie };
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import "server-only";
|
||||
import { mkdir, readFile, unlink, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
|
||||
// Ersetzt den früheren Supabase-Storage-Bucket "branding" durch ein
|
||||
// lokales Verzeichnis (Docker-Volume in Produktion, s. docker-compose.yml).
|
||||
export function brandingDir(): string {
|
||||
// turbopackIgnore: process.cwd() ist hier dynamisch, aber der Pfad
|
||||
// bleibt statisch unter "data/branding" – ohne den Kommentar versucht
|
||||
// Turbopack sonst, das gesamte Projektverzeichnis nach möglichen
|
||||
// dynamischen require()-Zielen zu durchsuchen (harmlos, aber unnötig).
|
||||
return (
|
||||
process.env.BRANDING_DIR ??
|
||||
path.join(/*turbopackIgnore: true*/ process.cwd(), "data", "branding")
|
||||
);
|
||||
}
|
||||
|
||||
// Nur einfache, von uns selbst vergebene Dateinamen zulassen
|
||||
// (`${kind}-${Date.now()}.${ext}`) – verhindert Path-Traversal über
|
||||
// Dateinamen aus der DB-Spalte logo_path/favicon_path.
|
||||
const SAFE_FILENAME = /^[a-zA-Z0-9_.-]+$/;
|
||||
|
||||
export function isSafeFilename(filename: string): boolean {
|
||||
return SAFE_FILENAME.test(filename) && !filename.includes("..");
|
||||
}
|
||||
|
||||
export async function saveBrandingFile(filename: string, data: Buffer): Promise<void> {
|
||||
const dir = brandingDir();
|
||||
await mkdir(dir, { recursive: true });
|
||||
await writeFile(path.join(dir, filename), data);
|
||||
}
|
||||
|
||||
export async function readBrandingFile(filename: string): Promise<Buffer | null> {
|
||||
if (!isSafeFilename(filename)) return null;
|
||||
try {
|
||||
return await readFile(path.join(brandingDir(), filename));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function removeBrandingFile(filename: string): Promise<void> {
|
||||
try {
|
||||
await unlink(path.join(brandingDir(), filename));
|
||||
} catch (err) {
|
||||
if ((err as NodeJS.ErrnoException).code !== "ENOENT") throw err;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import "server-only";
|
||||
import { query, queryOne } from "@/lib/db";
|
||||
import type { CodeItem } from "@/lib/types";
|
||||
|
||||
// "allergens"/"additives" sind identisch aufgebaute Tabellen (Kürzel +
|
||||
// Bezeichnung in DE/EN/PL). Tabellenname kommt nie aus Nutzereingaben,
|
||||
// sondern immer aus dem literal getypten Parameter unten – sicher für
|
||||
// String-Interpolation in der Query.
|
||||
export type CodeTable = "allergens" | "additives";
|
||||
|
||||
export async function listCodes(table: CodeTable): Promise<CodeItem[]> {
|
||||
return query<CodeItem>(`select * from ${table} order by sort`);
|
||||
}
|
||||
|
||||
export async function createCode(
|
||||
table: CodeTable,
|
||||
input: { code: string; name: string; name_en: string | null; name_pl: string | null }
|
||||
): Promise<CodeItem> {
|
||||
const maxRow = await queryOne<{ sort: number }>(
|
||||
`select sort from ${table} order by sort desc limit 1`
|
||||
);
|
||||
return (await queryOne<CodeItem>(
|
||||
`insert into ${table} (code, name, name_en, name_pl, sort) values ($1, $2, $3, $4, $5) returning *`,
|
||||
[input.code, input.name, input.name_en, input.name_pl, (maxRow?.sort ?? 0) + 1]
|
||||
))!;
|
||||
}
|
||||
|
||||
export async function updateCode(
|
||||
table: CodeTable,
|
||||
originalCode: string,
|
||||
input: { code: string; name: string; name_en: string | null; name_pl: string | null }
|
||||
): Promise<CodeItem | null> {
|
||||
return queryOne<CodeItem>(
|
||||
`update ${table} set code = $1, name = $2, name_en = $3, name_pl = $4 where code = $5 returning *`,
|
||||
[input.code, input.name, input.name_en, input.name_pl, originalCode]
|
||||
);
|
||||
}
|
||||
|
||||
export async function deleteCode(table: CodeTable, code: string): Promise<void> {
|
||||
await query(`delete from ${table} where code = $1`, [code]);
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import "server-only";
|
||||
import { query } from "@/lib/db";
|
||||
import type { MenuEntry } from "@/lib/types";
|
||||
|
||||
interface MenuEntryRow {
|
||||
id: string;
|
||||
menu_date: string;
|
||||
section_key: string;
|
||||
position: number;
|
||||
dish_id: string;
|
||||
name: string;
|
||||
name_en: string | null;
|
||||
name_pl: string | null;
|
||||
price: string;
|
||||
allergens: string[];
|
||||
additives: string[];
|
||||
}
|
||||
|
||||
/** Wochenplan-Einträge inkl. zugehörigem Gericht für den Zeitraum laden –
|
||||
* gemeinsam von der öffentlichen Speisekarte (Server Component) und
|
||||
* /api/menu-entries genutzt, damit der JOIN nur einmal gepflegt wird. */
|
||||
export async function loadMenuEntries(fromISO: string, toISO: string): Promise<MenuEntry[]> {
|
||||
const rows = await query<MenuEntryRow>(
|
||||
`select me.id, me.menu_date, me.section_key, me.position,
|
||||
d.id as dish_id, d.name, d.name_en, d.name_pl, d.price, d.allergens, d.additives
|
||||
from menu_entries me
|
||||
join dishes d on d.id = me.dish_id
|
||||
where me.menu_date between $1 and $2
|
||||
order by me.position, me.created_at`,
|
||||
[fromISO, toISO]
|
||||
);
|
||||
|
||||
return rows.map((r) => ({
|
||||
id: r.id,
|
||||
menu_date: r.menu_date,
|
||||
section_key: r.section_key,
|
||||
position: r.position,
|
||||
dish: {
|
||||
id: r.dish_id,
|
||||
name: r.name,
|
||||
name_en: r.name_en,
|
||||
name_pl: r.name_pl,
|
||||
price: Number(r.price),
|
||||
allergens: r.allergens,
|
||||
additives: r.additives,
|
||||
},
|
||||
}));
|
||||
}
|
||||
+12
-1
@@ -1,5 +1,16 @@
|
||||
import "server-only";
|
||||
import { Pool } from "pg";
|
||||
import { Pool, types } from "pg";
|
||||
|
||||
// pg gibt "date"-Spalten sonst als lokale Date-Objekte zurück (Zeitzonen-
|
||||
// Verschiebung möglich); die App vergleicht Datumswerte überall als reine
|
||||
// "YYYY-MM-DD"-Strings (siehe lib/menu.ts), daher Rohstring beibehalten.
|
||||
types.setTypeParser(types.builtins.DATE, (val) => val);
|
||||
|
||||
// pg gibt "numeric" (dishes.price) sonst als String zurück (Precision-
|
||||
// Schutz), die App erwartet aber überall eine JS-Zahl (wie zuvor von
|
||||
// Postgrest geliefert) – für Preise im niedrigen vierstelligen Bereich
|
||||
// mit 2 Nachkommastellen unproblematisch.
|
||||
types.setTypeParser(types.builtins.NUMERIC, (val) => Number(val));
|
||||
|
||||
// Next.js' Dev-Server lädt Module bei Hot-Reloads neu; ohne den
|
||||
// globalThis-Cache würde bei jedem Speichern ein neuer Pool (und damit
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import "server-only";
|
||||
import { queryOne } from "@/lib/db";
|
||||
|
||||
export interface Settings {
|
||||
colors: Record<string, string>;
|
||||
logo_path: string | null;
|
||||
favicon_path: string | null;
|
||||
}
|
||||
|
||||
export async function getSettings(): Promise<Settings | null> {
|
||||
return queryOne<Settings>(
|
||||
"select colors, logo_path, favicon_path from settings where id = 1"
|
||||
);
|
||||
}
|
||||
@@ -185,7 +185,7 @@ const de = {
|
||||
},
|
||||
passkeys: {
|
||||
title: "Passkeys",
|
||||
hint: "Mit einem Passkey (Fingerabdruck, Gesichtserkennung oder Sicherheitsschlüssel) kannst du dich künftig ohne Passwort anmelden. Passkeys gelten pro Domain – für den Live-Betrieb muss die Domain in der Supabase-Konfiguration hinterlegt sein.",
|
||||
hint: "Mit einem Passkey (Fingerabdruck, Gesichtserkennung oder Sicherheitsschlüssel) kannst du dich künftig ohne Passwort anmelden. Passkeys gelten pro Domain – nach einem Domainwechsel müssen sie neu registriert werden.",
|
||||
register: "Neuen Passkey registrieren",
|
||||
empty: "Noch keine Passkeys registriert.",
|
||||
createdOn: "– angelegt am {date}",
|
||||
@@ -439,7 +439,7 @@ const en: Dict = {
|
||||
},
|
||||
passkeys: {
|
||||
title: "Passkeys",
|
||||
hint: "With a passkey (fingerprint, face recognition, or a security key) you can sign in without a password in the future. Passkeys are bound to a domain – for production use, the domain must be configured in Supabase.",
|
||||
hint: "With a passkey (fingerprint, face recognition, or a security key) you can sign in without a password in the future. Passkeys are bound to a domain – after a domain change they need to be registered again.",
|
||||
register: "Register new passkey",
|
||||
empty: "No passkeys registered yet.",
|
||||
createdOn: "– created on {date}",
|
||||
@@ -691,7 +691,7 @@ const pl: Dict = {
|
||||
},
|
||||
passkeys: {
|
||||
title: "Klucze dostępu",
|
||||
hint: "Dzięki kluczowi dostępu (odcisk palca, rozpoznawanie twarzy lub klucz bezpieczeństwa) możesz w przyszłości logować się bez hasła. Klucze dostępu są przypisane do domeny – w środowisku produkcyjnym domena musi być skonfigurowana w Supabase.",
|
||||
hint: "Dzięki kluczowi dostępu (odcisk palca, rozpoznawanie twarzy lub klucz bezpieczeństwa) możesz w przyszłości logować się bez hasła. Klucze dostępu są przypisane do domeny – po zmianie domeny trzeba je zarejestrować ponownie.",
|
||||
register: "Zarejestruj nowy klucz dostępu",
|
||||
empty: "Nie zarejestrowano jeszcze żadnych kluczy dostępu.",
|
||||
createdOn: "– utworzono {date}",
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
import "server-only";
|
||||
import { createClient as createSupabaseClient } from "@supabase/supabase-js";
|
||||
|
||||
// Service-Role-Client: umgeht RLS. Ausschließlich serverseitig verwenden
|
||||
// (Benutzerverwaltung durch den Admin).
|
||||
export function createAdminClient() {
|
||||
return createSupabaseClient(
|
||||
process.env.NEXT_PUBLIC_SUPABASE_URL!,
|
||||
process.env.SUPABASE_SERVICE_ROLE_KEY!,
|
||||
{
|
||||
auth: { persistSession: false, autoRefreshToken: false },
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
import { createBrowserClient } from "@supabase/ssr";
|
||||
|
||||
// Browser-Client (Client Components). Passkey-Support ist bei Supabase
|
||||
// derzeit als experimentelles Feature markiert und muss aktiviert werden.
|
||||
export function createClient() {
|
||||
return createBrowserClient(
|
||||
process.env.NEXT_PUBLIC_SUPABASE_URL!,
|
||||
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
|
||||
{
|
||||
auth: {
|
||||
experimental: { passkey: true },
|
||||
},
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
import { createServerClient } from "@supabase/ssr";
|
||||
import { cookies } from "next/headers";
|
||||
|
||||
// Server-Client (Server Components, Route Handler, Server Actions).
|
||||
// Muss pro Request neu erzeugt werden.
|
||||
export async function createClient() {
|
||||
const cookieStore = await cookies();
|
||||
|
||||
return createServerClient(
|
||||
process.env.NEXT_PUBLIC_SUPABASE_URL!,
|
||||
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
|
||||
{
|
||||
cookies: {
|
||||
getAll() {
|
||||
return cookieStore.getAll();
|
||||
},
|
||||
setAll(cookiesToSet) {
|
||||
try {
|
||||
cookiesToSet.forEach(({ name, value, options }) =>
|
||||
cookieStore.set(name, value, options)
|
||||
);
|
||||
} catch {
|
||||
// In Server Components dürfen keine Cookies gesetzt werden –
|
||||
// das Session-Refresh übernimmt proxy.ts.
|
||||
}
|
||||
},
|
||||
},
|
||||
}
|
||||
);
|
||||
}
|
||||
+2
-2
@@ -87,12 +87,12 @@ export const COLOR_VARS: Record<string, string> = {
|
||||
|
||||
export function logoUrl(path: string | null | undefined): string | null {
|
||||
if (!path) return null;
|
||||
return `${process.env.NEXT_PUBLIC_SUPABASE_URL}/storage/v1/object/public/branding/${path}`;
|
||||
return `/branding/${path}`;
|
||||
}
|
||||
|
||||
export function faviconUrl(path: string | null | undefined): string | null {
|
||||
if (!path) return null;
|
||||
return `${process.env.NEXT_PUBLIC_SUPABASE_URL}/storage/v1/object/public/branding/${path}`;
|
||||
return `/branding/${path}`;
|
||||
}
|
||||
|
||||
export const SITE_TITLE = process.env.SITE_TITLE?.trim() || "Canteen Menu";
|
||||
|
||||
Reference in New Issue
Block a user