Admin-Bereich: Benutzerverwaltung (Service-Role, serverseitig), Farben und Logo-Upload
This commit is contained in:
@@ -0,0 +1,5 @@
|
||||
import DesignEditor from "@/components/DesignEditor";
|
||||
|
||||
export default function DesignPage() {
|
||||
return <DesignEditor />;
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import Link from "next/link";
|
||||
import { redirect } from "next/navigation";
|
||||
import { createClient } from "@/lib/supabase/server";
|
||||
|
||||
export default async function AdminLayout({
|
||||
children,
|
||||
}: {
|
||||
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");
|
||||
|
||||
return (
|
||||
<div className="flex-1 flex flex-col">
|
||||
<header className="bg-[var(--c-primary-dark)] text-white">
|
||||
<div className="max-w-[1600px] mx-auto w-full px-4 py-3 flex flex-wrap items-center gap-x-5 gap-y-2">
|
||||
<span className="font-bold">Verwaltung</span>
|
||||
<nav className="flex flex-wrap gap-x-4 gap-y-1 text-sm">
|
||||
<Link href="/admin" className="hover:underline">
|
||||
Benutzer
|
||||
</Link>
|
||||
<Link href="/admin/design" className="hover:underline">
|
||||
Design
|
||||
</Link>
|
||||
<Link href="/intern" className="hover:underline">
|
||||
Kantinen-Bereich
|
||||
</Link>
|
||||
<Link href="/" className="hover:underline">
|
||||
Zur Speisekarte
|
||||
</Link>
|
||||
</nav>
|
||||
<div className="ml-auto flex items-center gap-3 text-sm">
|
||||
<span className="text-white/70">
|
||||
{profile.full_name || user.email}
|
||||
</span>
|
||||
<form action="/logout" method="post">
|
||||
<button type="submit" className="btn btn-del">
|
||||
Abmelden
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
<main className="max-w-[1600px] mx-auto w-full px-4 py-6 flex-1">
|
||||
{children}
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import UserManager from "@/components/UserManager";
|
||||
|
||||
export default function AdminPage() {
|
||||
return <UserManager />;
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { createClient } from "@/lib/supabase/server";
|
||||
import { createAdminClient } from "@/lib/supabase/admin";
|
||||
|
||||
// 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.
|
||||
|
||||
async function requireAdmin() {
|
||||
const supabase = await createClient();
|
||||
const {
|
||||
data: { user },
|
||||
} = await supabase.auth.getUser();
|
||||
if (!user) return null;
|
||||
|
||||
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 };
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const ctx = await requireAdmin();
|
||||
if (!ctx) return NextResponse.json({ error: "Nicht berechtigt." }, { status: 403 });
|
||||
|
||||
const body = await request.json().catch(() => null);
|
||||
const { email, password, full_name, role } = body ?? {};
|
||||
if (!email || !password || !["admin", "staff"].includes(role)) {
|
||||
return NextResponse.json({ error: "Ungültige Eingaben." }, { status: 400 });
|
||||
}
|
||||
if (String(password).length < 8) {
|
||||
return NextResponse.json(
|
||||
{ error: "Das Passwort muss mindestens 8 Zeichen lang sein." },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
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 }
|
||||
);
|
||||
}
|
||||
return NextResponse.json({ id: data.user?.id });
|
||||
}
|
||||
|
||||
export async function PATCH(request: Request) {
|
||||
const ctx = await requireAdmin();
|
||||
if (!ctx) return NextResponse.json({ error: "Nicht berechtigt." }, { status: 403 });
|
||||
|
||||
const body = await request.json().catch(() => null);
|
||||
const { id, full_name, role, password } = body ?? {};
|
||||
if (!id || (role && !["admin", "staff"].includes(role))) {
|
||||
return NextResponse.json({ error: "Ungültige Eingaben." }, { status: 400 });
|
||||
}
|
||||
// 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") {
|
||||
return NextResponse.json(
|
||||
{ error: "Du kannst dir nicht selbst die Admin-Rolle entziehen." },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
if (password) {
|
||||
if (String(password).length < 8) {
|
||||
return NextResponse.json(
|
||||
{ error: "Das Passwort muss mindestens 8 Zeichen lang sein." },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
const { error } = await ctx.admin.auth.admin.updateUserById(id, { password });
|
||||
if (error) return NextResponse.json({ error: error.message }, { status: 400 });
|
||||
}
|
||||
|
||||
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 });
|
||||
}
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
|
||||
export async function DELETE(request: Request) {
|
||||
const ctx = await requireAdmin();
|
||||
if (!ctx) return NextResponse.json({ error: "Nicht berechtigt." }, { status: 403 });
|
||||
|
||||
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) {
|
||||
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 });
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { createClient } from "@/lib/supabase/client";
|
||||
import { COLOR_LABELS, DEFAULT_COLORS, logoUrl } from "@/lib/types";
|
||||
|
||||
export default function DesignEditor() {
|
||||
const supabase = useMemo(() => createClient(), []);
|
||||
const router = useRouter();
|
||||
const [colors, setColors] = useState<Record<string, string>>(DEFAULT_COLORS);
|
||||
const [logoPath, setLogoPath] = useState<string | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [info, setInfo] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
const { data, error } = await supabase
|
||||
.from("settings")
|
||||
.select("colors, logo_path")
|
||||
.eq("id", 1)
|
||||
.maybeSingle();
|
||||
if (error) {
|
||||
setError(`Laden fehlgeschlagen: ${error.message}`);
|
||||
return;
|
||||
}
|
||||
setColors({ ...DEFAULT_COLORS, ...(data?.colors ?? {}) });
|
||||
setLogoPath(data?.logo_path ?? null);
|
||||
}, [supabase]);
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, [load]);
|
||||
|
||||
async function saveColors() {
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
setInfo(null);
|
||||
const { error } = await supabase
|
||||
.from("settings")
|
||||
.update({ colors })
|
||||
.eq("id", 1);
|
||||
if (error) setError(`Speichern fehlgeschlagen: ${error.message}`);
|
||||
else {
|
||||
setInfo("Farben gespeichert.");
|
||||
router.refresh();
|
||||
}
|
||||
setBusy(false);
|
||||
}
|
||||
|
||||
async function resetColors() {
|
||||
setColors(DEFAULT_COLORS);
|
||||
}
|
||||
|
||||
async function uploadLogo(e: React.ChangeEvent<HTMLInputElement>) {
|
||||
const file = e.target.files?.[0];
|
||||
e.target.value = "";
|
||||
if (!file) return;
|
||||
if (!/^image\//.test(file.type)) {
|
||||
setError("Bitte eine Bilddatei auswählen (PNG, JPG, SVG, WebP).");
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
setInfo(null);
|
||||
|
||||
const ext = file.name.split(".").pop()?.toLowerCase() ?? "png";
|
||||
const path = `logo-${Date.now()}.${ext}`;
|
||||
const { error: uploadError } = await supabase.storage
|
||||
.from("branding")
|
||||
.upload(path, file, { contentType: file.type });
|
||||
if (uploadError) {
|
||||
setError(`Upload fehlgeschlagen: ${uploadError.message}`);
|
||||
setBusy(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const oldPath = logoPath;
|
||||
const { error: settingsError } = await supabase
|
||||
.from("settings")
|
||||
.update({ logo_path: path })
|
||||
.eq("id", 1);
|
||||
if (settingsError) {
|
||||
setError(`Speichern fehlgeschlagen: ${settingsError.message}`);
|
||||
setBusy(false);
|
||||
return;
|
||||
}
|
||||
if (oldPath) {
|
||||
await supabase.storage.from("branding").remove([oldPath]);
|
||||
}
|
||||
setLogoPath(path);
|
||||
setInfo("Logo aktualisiert.");
|
||||
router.refresh();
|
||||
setBusy(false);
|
||||
}
|
||||
|
||||
async function removeLogo() {
|
||||
if (!logoPath) return;
|
||||
if (!window.confirm("Logo wirklich entfernen?")) return;
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
const { error } = await supabase
|
||||
.from("settings")
|
||||
.update({ logo_path: null })
|
||||
.eq("id", 1);
|
||||
if (error) {
|
||||
setError(`Speichern fehlgeschlagen: ${error.message}`);
|
||||
} else {
|
||||
await supabase.storage.from("branding").remove([logoPath]);
|
||||
setLogoPath(null);
|
||||
setInfo("Logo entfernt.");
|
||||
router.refresh();
|
||||
}
|
||||
setBusy(false);
|
||||
}
|
||||
|
||||
const currentLogo = logoUrl(logoPath);
|
||||
|
||||
return (
|
||||
<div className="max-w-3xl space-y-6">
|
||||
<h1 className="text-xl font-bold text-[var(--c-primary)]">Design</h1>
|
||||
|
||||
{error && (
|
||||
<p className="text-sm text-[var(--c-del)]" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
{info && <p className="text-sm text-green-700">{info}</p>}
|
||||
|
||||
<section className="card">
|
||||
<h2 className="font-semibold mb-3">Logo</h2>
|
||||
<p className="text-sm text-gray-600 mb-3">
|
||||
Das Logo wird zentriert über der Speisekarte angezeigt.
|
||||
</p>
|
||||
{currentLogo ? (
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img
|
||||
src={currentLogo}
|
||||
alt="Aktuelles Logo"
|
||||
className="h-20 object-contain mb-3 border border-gray-200 rounded p-2"
|
||||
/>
|
||||
) : (
|
||||
<p className="text-sm text-gray-400 mb-3">Kein Logo hinterlegt.</p>
|
||||
)}
|
||||
<div className="flex gap-2 items-center">
|
||||
<label className="btn btn-primary cursor-pointer">
|
||||
Logo hochladen
|
||||
<input
|
||||
type="file"
|
||||
accept="image/*"
|
||||
className="hidden"
|
||||
onChange={uploadLogo}
|
||||
disabled={busy}
|
||||
/>
|
||||
</label>
|
||||
{currentLogo && (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-del"
|
||||
onClick={removeLogo}
|
||||
disabled={busy}
|
||||
>
|
||||
Logo entfernen
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="card">
|
||||
<h2 className="font-semibold mb-3">Farbgebung</h2>
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
{Object.entries(COLOR_LABELS).map(([key, label]) => (
|
||||
<label key={key} className="flex items-center gap-3 text-sm">
|
||||
<input
|
||||
type="color"
|
||||
value={colors[key] ?? "#000000"}
|
||||
onChange={(e) =>
|
||||
setColors({ ...colors, [key]: e.target.value })
|
||||
}
|
||||
className="h-9 w-14 cursor-pointer border border-gray-300 rounded"
|
||||
/>
|
||||
{label}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
<div className="flex gap-2 mt-4">
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-add"
|
||||
onClick={saveColors}
|
||||
disabled={busy}
|
||||
>
|
||||
Farben speichern
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-neutral"
|
||||
onClick={resetColors}
|
||||
disabled={busy}
|
||||
>
|
||||
Auf Standard zurücksetzen
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { createClient } from "@/lib/supabase/client";
|
||||
import type { Profile, Role } from "@/lib/types";
|
||||
|
||||
interface UserForm {
|
||||
id: string | null; // null = neuer Benutzer
|
||||
email: string;
|
||||
full_name: string;
|
||||
role: Role;
|
||||
password: string; // bei Bearbeitung optional (leer = unverändert)
|
||||
}
|
||||
|
||||
const EMPTY_FORM: UserForm = {
|
||||
id: null,
|
||||
email: "",
|
||||
full_name: "",
|
||||
role: "staff",
|
||||
password: "",
|
||||
};
|
||||
|
||||
const ROLE_LABELS: Record<Role, string> = {
|
||||
admin: "Administrator",
|
||||
staff: "Kantinenmitarbeiter",
|
||||
};
|
||||
|
||||
export default function UserManager() {
|
||||
const supabase = useMemo(() => createClient(), []);
|
||||
const [profiles, setProfiles] = useState<Profile[]>([]);
|
||||
const [me, setMe] = useState<string | null>(null);
|
||||
const [form, setForm] = useState<UserForm | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
const [{ data: profileData, error: profileError }, { data: userData }] =
|
||||
await Promise.all([
|
||||
supabase.from("profiles").select("*").order("created_at"),
|
||||
supabase.auth.getUser(),
|
||||
]);
|
||||
if (profileError) setError(`Laden fehlgeschlagen: ${profileError.message}`);
|
||||
else setProfiles(profileData as Profile[]);
|
||||
setMe(userData.user?.id ?? null);
|
||||
}, [supabase]);
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, [load]);
|
||||
|
||||
async function callApi(method: string, body: unknown): Promise<boolean> {
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
const res = await fetch("/api/admin/users", {
|
||||
method,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => null);
|
||||
setError(data?.error ?? `Fehler (${res.status})`);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : String(err));
|
||||
return false;
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function save(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!form) return;
|
||||
const ok = form.id
|
||||
? await callApi("PATCH", {
|
||||
id: form.id,
|
||||
full_name: form.full_name,
|
||||
role: form.role,
|
||||
password: form.password || undefined,
|
||||
})
|
||||
: await callApi("POST", {
|
||||
email: form.email,
|
||||
full_name: form.full_name,
|
||||
role: form.role,
|
||||
password: form.password,
|
||||
});
|
||||
if (ok) {
|
||||
setForm(null);
|
||||
await load();
|
||||
}
|
||||
}
|
||||
|
||||
async function remove(profile: Profile) {
|
||||
if (
|
||||
!window.confirm(
|
||||
`Benutzer „${profile.email}“ wirklich löschen? Der Zugang wird dauerhaft entfernt.`
|
||||
)
|
||||
)
|
||||
return;
|
||||
if (await callApi("DELETE", { id: profile.id })) await load();
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="max-w-3xl">
|
||||
<div className="flex items-center gap-3 mb-4">
|
||||
<h1 className="text-xl font-bold text-[var(--c-primary)] mr-auto">
|
||||
Benutzer
|
||||
</h1>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-add"
|
||||
onClick={() => setForm(EMPTY_FORM)}
|
||||
>
|
||||
Neuer Benutzer
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<p className="mb-3 text-sm text-[var(--c-del)]" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{form && (
|
||||
<form onSubmit={save} className="card mb-4 space-y-3">
|
||||
<h2 className="font-semibold">
|
||||
{form.id ? "Benutzer bearbeiten" : "Neuer Benutzer"}
|
||||
</h2>
|
||||
{!form.id && (
|
||||
<div>
|
||||
<label className="label" htmlFor="user-email">
|
||||
E-Mail-Adresse
|
||||
</label>
|
||||
<input
|
||||
id="user-email"
|
||||
type="email"
|
||||
className="input"
|
||||
value={form.email}
|
||||
onChange={(e) => setForm({ ...form, email: e.target.value })}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<div>
|
||||
<label className="label" htmlFor="user-name">
|
||||
Name
|
||||
</label>
|
||||
<input
|
||||
id="user-name"
|
||||
className="input"
|
||||
value={form.full_name}
|
||||
onChange={(e) => setForm({ ...form, full_name: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
<div className="max-w-60">
|
||||
<label className="label" htmlFor="user-role">
|
||||
Rolle
|
||||
</label>
|
||||
<select
|
||||
id="user-role"
|
||||
className="input"
|
||||
value={form.role}
|
||||
onChange={(e) =>
|
||||
setForm({ ...form, role: e.target.value as Role })
|
||||
}
|
||||
>
|
||||
<option value="staff">Kantinenmitarbeiter</option>
|
||||
<option value="admin">Administrator</option>
|
||||
</select>
|
||||
</div>
|
||||
<div className="max-w-60">
|
||||
<label className="label" htmlFor="user-password">
|
||||
{form.id ? "Neues Passwort (optional)" : "Passwort"}
|
||||
</label>
|
||||
<input
|
||||
id="user-password"
|
||||
type="password"
|
||||
className="input"
|
||||
value={form.password}
|
||||
onChange={(e) => setForm({ ...form, password: e.target.value })}
|
||||
minLength={8}
|
||||
required={!form.id}
|
||||
autoComplete="new-password"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<button type="submit" className="btn btn-add" disabled={busy}>
|
||||
Speichern
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-neutral"
|
||||
onClick={() => setForm(null)}
|
||||
>
|
||||
Abbrechen
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
|
||||
<ul className="divide-y divide-gray-200 border border-gray-200 rounded-md bg-white">
|
||||
{profiles.map((p) => (
|
||||
<li key={p.id} className="flex items-center gap-3 px-4 py-2 text-sm">
|
||||
<span className="mr-auto">
|
||||
<span className="font-semibold">{p.full_name || p.email}</span>{" "}
|
||||
<span className="text-gray-500">
|
||||
– {p.email} – {ROLE_LABELS[p.role]}
|
||||
</span>
|
||||
{p.id === me && <span className="text-gray-400"> (du)</span>}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary"
|
||||
onClick={() =>
|
||||
setForm({
|
||||
id: p.id,
|
||||
email: p.email,
|
||||
full_name: p.full_name,
|
||||
role: p.role,
|
||||
password: "",
|
||||
})
|
||||
}
|
||||
>
|
||||
Bearbeiten
|
||||
</button>
|
||||
{p.id !== me && (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-del"
|
||||
onClick={() => remove(p)}
|
||||
>
|
||||
Löschen
|
||||
</button>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user