feat(admin): admin panel with overview, users, audit logs, storage, AI config, settings

Sticky sidebar with back-to-app link. Overview: user counts, recipe photos, AI calls/month.
User management with role/tier editing. Audit log (all admin actions).
Storage page with photo breakdown by tier. AI config showing DB vs .env key source.
Site settings page to override .env values at runtime (encrypted in DB).
This commit is contained in:
Arnaud
2026-07-01 08:10:59 +02:00
parent b2d592afe8
commit cba5d9c3ac
14 changed files with 1197 additions and 0 deletions
+108
View File
@@ -0,0 +1,108 @@
import type { Metadata } from "next";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { CheckCircle, XCircle, Database, Cpu } from "lucide-react";
import Link from "next/link";
import { getAllSiteSettings } from "@/lib/site-settings";
export const metadata: Metadata = { title: "AI Config" };
function resolveProvider(settings: Record<string, { value: string | null }>) {
if (settings["OPENROUTER_API_KEY"]?.value) return { provider: "OpenRouter", description: "Routes to many models via openrouter.ai" };
if (settings["OPENAI_API_KEY"]?.value) return { provider: "OpenAI", description: "Direct OpenAI API (GPT-4 etc.)" };
if (settings["ANTHROPIC_API_KEY"]?.value) return { provider: "Anthropic", description: "Direct Anthropic API (Claude models)" };
const url = settings["OLLAMA_BASE_URL"]?.value || "http://localhost:11434";
return { provider: "Ollama", description: `Local inference at ${url}` };
}
export default async function AdminAiConfigPage() {
const settings = await getAllSiteSettings();
const active = resolveProvider(settings);
const keyRows = [
{ key: "OPENROUTER_API_KEY", label: "OPENROUTER_API_KEY" },
{ key: "OPENAI_API_KEY", label: "OPENAI_API_KEY" },
{ key: "ANTHROPIC_API_KEY", label: "ANTHROPIC_API_KEY" },
];
return (
<div className="space-y-6">
<div>
<h1 className="text-2xl font-bold tracking-tight">AI Configuration</h1>
<p className="text-muted-foreground text-sm mt-1">
Current AI provider settings. Override values in{" "}
<Link href="/admin/settings" className="text-primary underline-offset-4 hover:underline">
Site Settings
</Link>
.
</p>
</div>
<Card>
<CardHeader>
<CardTitle className="text-base">Active Provider</CardTitle>
</CardHeader>
<CardContent>
<div className="flex items-center gap-3">
<Badge className="text-sm px-3 py-1">{active.provider}</Badge>
<span className="text-muted-foreground text-sm">{active.description}</span>
</div>
<p className="text-xs text-muted-foreground mt-3">
Priority: OpenRouter OpenAI Anthropic Ollama (first configured key wins).
</p>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="text-base">API Keys</CardTitle>
</CardHeader>
<CardContent>
{keyRows.map(({ key, label }) => {
const meta = settings[key];
const present = !!meta?.value;
return (
<div key={key} className="flex items-center justify-between py-2 border-b last:border-0">
<div className="flex items-center gap-2">
{present ? (
<CheckCircle className="h-4 w-4 text-green-500" />
) : (
<XCircle className="h-4 w-4 text-muted-foreground" />
)}
<span className="font-mono text-sm">{label}</span>
</div>
<div className="flex items-center gap-2">
{present && meta?.fromDb && (
<span className="flex items-center gap-1 text-xs text-muted-foreground">
<Database className="h-3 w-3" /> DB override
</span>
)}
{present && !meta?.fromDb && (
<span className="flex items-center gap-1 text-xs text-muted-foreground">
<Cpu className="h-3 w-3" /> from .env
</span>
)}
<Badge variant={present ? "default" : "secondary"}>
{present ? "Configured" : "Not set"}
</Badge>
</div>
</div>
);
})}
<div className="flex items-center justify-between py-2 border-b">
<span className="font-mono text-sm text-muted-foreground">OLLAMA_BASE_URL</span>
<span className="text-sm text-muted-foreground font-mono">
{settings["OLLAMA_BASE_URL"]?.value || "http://localhost:11434 (default)"}
</span>
</div>
<div className="flex items-center justify-between py-2">
<span className="font-mono text-sm text-muted-foreground">OPENROUTER_DEFAULT_MODEL</span>
<span className="text-sm text-muted-foreground font-mono">
{settings["OPENROUTER_DEFAULT_MODEL"]?.value || "google/gemini-flash-1.5 (default)"}
</span>
</div>
</CardContent>
</Card>
</div>
);
}
+114
View File
@@ -0,0 +1,114 @@
import type { Metadata } from "next";
import { db, auditLogs, users, eq, desc } from "@epicure/db";
export const metadata: Metadata = { title: "Audit Logs" };
const PAGE_SIZE = 50;
interface PageProps {
searchParams: Promise<{ page?: string }>;
}
export default async function AdminAuditLogsPage({ searchParams }: PageProps) {
const { page: pageParam } = await searchParams;
const page = Math.max(1, parseInt(pageParam ?? "1", 10));
const offset = (page - 1) * PAGE_SIZE;
const rows = await db
.select({
id: auditLogs.id,
action: auditLogs.action,
targetType: auditLogs.targetType,
targetId: auditLogs.targetId,
metadata: auditLogs.metadata,
createdAt: auditLogs.createdAt,
actorName: users.name,
actorEmail: users.email,
})
.from(auditLogs)
.leftJoin(users, eq(auditLogs.userId, users.id))
.orderBy(desc(auditLogs.createdAt))
.limit(PAGE_SIZE)
.offset(offset);
return (
<div className="space-y-6">
<div>
<h1 className="text-2xl font-bold tracking-tight">Audit Logs</h1>
<p className="text-muted-foreground text-sm mt-1">
Admin actions recorded for accountability. Page {page}.
</p>
</div>
<div className="rounded-md border overflow-x-auto">
<table className="w-full text-sm">
<thead className="border-b bg-muted/50">
<tr>
<th className="px-4 py-3 text-left font-medium whitespace-nowrap">Actor</th>
<th className="px-4 py-3 text-left font-medium whitespace-nowrap">Action</th>
<th className="px-4 py-3 text-left font-medium whitespace-nowrap">Target</th>
<th className="px-4 py-3 text-left font-medium whitespace-nowrap">Metadata</th>
<th className="px-4 py-3 text-left font-medium whitespace-nowrap">Timestamp</th>
</tr>
</thead>
<tbody>
{rows.length === 0 ? (
<tr>
<td colSpan={5} className="px-4 py-8 text-center text-muted-foreground">
No audit log entries yet.
</td>
</tr>
) : (
rows.map((row) => (
<tr key={row.id} className="border-b last:border-0 hover:bg-muted/30">
<td className="px-4 py-3">
<div className="font-medium">{row.actorName ?? "System"}</div>
{row.actorEmail && (
<div className="text-xs text-muted-foreground">{row.actorEmail}</div>
)}
</td>
<td className="px-4 py-3 font-mono text-xs">{row.action}</td>
<td className="px-4 py-3 text-muted-foreground text-xs">
{row.targetType ? (
<span>
{row.targetType}
{row.targetId ? `: ${row.targetId.slice(0, 8)}` : ""}
</span>
) : (
"—"
)}
</td>
<td className="px-4 py-3 font-mono text-xs text-muted-foreground max-w-xs truncate">
{row.metadata ?? "—"}
</td>
<td className="px-4 py-3 text-muted-foreground whitespace-nowrap">
{row.createdAt.toLocaleString()}
</td>
</tr>
))
)}
</tbody>
</table>
</div>
<div className="flex gap-2">
{page > 1 && (
<a
href={`/admin/audit-logs?page=${page - 1}`}
className="rounded-md border px-3 py-1 text-sm hover:bg-accent"
>
Previous
</a>
)}
{rows.length === PAGE_SIZE && (
<a
href={`/admin/audit-logs?page=${page + 1}`}
className="rounded-md border px-3 py-1 text-sm hover:bg-accent"
>
Next
</a>
)}
</div>
</div>
);
}
+61
View File
@@ -0,0 +1,61 @@
import { redirect } from "next/navigation";
import { headers } from "next/headers";
import { auth } from "@/lib/auth/server";
import { db, users, eq } from "@epicure/db";
import Link from "next/link";
import { Shield, Users, BookOpen, Settings, BarChart3, ClipboardList, HardDrive, Bot, ArrowLeft } from "lucide-react";
import { cn } from "@/lib/utils";
const adminNav = [
{ href: "/admin", label: "Overview", icon: BarChart3 },
{ href: "/admin/users", label: "Users", icon: Users },
{ href: "/admin/recipes", label: "Recipes", icon: BookOpen },
{ href: "/admin/audit-logs", label: "Audit Logs", icon: ClipboardList },
{ href: "/admin/storage", label: "Storage", icon: HardDrive },
{ href: "/admin/ai-config", label: "AI Config", icon: Bot },
{ href: "/admin/settings", label: "Settings", icon: Settings },
];
export default async function AdminLayout({ children }: { children: React.ReactNode }) {
const session = await auth.api.getSession({ headers: await headers() });
if (!session) redirect("/login");
const [dbUser] = await db.select({ role: users.role }).from(users).where(eq(users.id, session.user.id));
if (dbUser?.role !== "admin") redirect("/recipes");
return (
<div className="flex min-h-screen">
<aside className="w-56 border-r bg-muted/30 flex flex-col sticky top-0 h-screen">
<div className="flex items-center gap-2 p-4 border-b font-semibold">
<Shield className="h-4 w-4 text-destructive" />
Admin
</div>
<nav className="flex flex-col gap-1 p-2 flex-1">
{adminNav.map(({ href, label, icon: Icon }) => (
<Link
key={href}
href={href}
className={cn(
"flex items-center gap-2 rounded-md px-3 py-2 text-sm transition-colors",
"hover:bg-accent hover:text-accent-foreground"
)}
>
<Icon className="h-4 w-4" />
{label}
</Link>
))}
</nav>
<div className="p-2 border-t">
<Link
href="/recipes"
className="flex items-center gap-2 rounded-md px-3 py-2 text-sm text-muted-foreground hover:text-foreground hover:bg-accent transition-colors"
>
<ArrowLeft className="h-4 w-4" />
Back to app
</Link>
</div>
</aside>
<main className="flex-1 p-8 overflow-auto">{children}</main>
</div>
);
}
+51
View File
@@ -0,0 +1,51 @@
import type { Metadata } from "next";
import { db } from "@epicure/db";
import { users, recipes, userUsage, recipePhotos } from "@epicure/db";
import { count, eq, sql } from "@epicure/db";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Users, BookOpen, Sparkles, Image } from "lucide-react";
export const metadata: Metadata = { title: "Admin Overview" };
export default async function AdminPage() {
const currentMonth = new Date().toISOString().slice(0, 7);
const [userCount, recipeCount, proUserCount, aiUsage, imageCount] = await Promise.all([
db.select({ count: count() }).from(users).then((r) => r[0]),
db.select({ count: count() }).from(recipes).then((r) => r[0]),
db.select({ count: count() }).from(users).where(eq(users.tier, "pro")).then((r) => r[0]),
db
.select({ total: sql<string>`coalesce(sum(${userUsage.aiCallsUsed}), 0)` })
.from(userUsage)
.where(eq(userUsage.month, currentMonth))
.then((r) => r[0]),
db.select({ count: count() }).from(recipePhotos).then((r) => r[0]),
]);
const stats = [
{ label: "Total Users", value: userCount?.count ?? 0, sub: `${proUserCount?.count ?? 0} pro`, icon: Users },
{ label: "Total Recipes", value: recipeCount?.count ?? 0, icon: BookOpen },
{ label: "AI Calls This Month", value: Number(aiUsage?.total ?? 0), icon: Sparkles },
{ label: "Recipe Photos", value: imageCount?.count ?? 0, icon: Image },
];
return (
<div className="space-y-6">
<h1 className="text-2xl font-bold tracking-tight">Overview</h1>
<div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
{stats.map(({ label, value, sub, icon: Icon }) => (
<Card key={label}>
<CardHeader className="flex flex-row items-center justify-between pb-2">
<CardTitle className="text-sm font-medium text-muted-foreground">{label}</CardTitle>
<Icon className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{value.toLocaleString()}</div>
{sub && <p className="text-xs text-muted-foreground mt-1">{sub}</p>}
</CardContent>
</Card>
))}
</div>
</div>
);
}
+99
View File
@@ -0,0 +1,99 @@
import type { Metadata } from "next";
import { db, recipes, users, eq, desc } from "@epicure/db";
import { Badge } from "@/components/ui/badge";
import Link from "next/link";
export const metadata: Metadata = { title: "Recipe Moderation" };
const VISIBILITY_COLORS = {
public: "default",
unlisted: "outline",
private: "secondary",
} as const;
export default async function AdminRecipesPage() {
const publicRecipes = await db
.select({
id: recipes.id,
title: recipes.title,
visibility: recipes.visibility,
createdAt: recipes.createdAt,
authorName: users.name,
authorId: users.id,
})
.from(recipes)
.leftJoin(users, eq(recipes.authorId, users.id))
.where(eq(recipes.visibility, "public"))
.orderBy(desc(recipes.createdAt))
.limit(200);
return (
<div className="space-y-6">
<div>
<h1 className="text-2xl font-bold tracking-tight">Recipe Moderation</h1>
<p className="text-muted-foreground text-sm mt-1">
Public recipes sorted by newest. Review and decide manually.
</p>
</div>
<div className="rounded-md border">
<table className="w-full text-sm">
<thead className="border-b bg-muted/50">
<tr>
<th className="px-4 py-3 text-left font-medium">Title</th>
<th className="px-4 py-3 text-left font-medium">Author</th>
<th className="px-4 py-3 text-left font-medium">Visibility</th>
<th className="px-4 py-3 text-left font-medium">Created</th>
<th className="px-4 py-3 text-left font-medium">Link</th>
</tr>
</thead>
<tbody>
{publicRecipes.length === 0 ? (
<tr>
<td colSpan={5} className="px-4 py-8 text-center text-muted-foreground">
No public recipes yet.
</td>
</tr>
) : (
publicRecipes.map((recipe) => (
<tr key={recipe.id} className="border-b last:border-0 hover:bg-muted/30">
<td className="px-4 py-3 font-medium">{recipe.title}</td>
<td className="px-4 py-3 text-muted-foreground">
{recipe.authorId ? (
<Link
href={`/admin/users/${recipe.authorId}`}
className="hover:underline underline-offset-4"
>
{recipe.authorName ?? "Unknown"}
</Link>
) : (
<span>{recipe.authorName ?? "Unknown"}</span>
)}
</td>
<td className="px-4 py-3">
<Badge variant={VISIBILITY_COLORS[recipe.visibility]}>
{recipe.visibility}
</Badge>
</td>
<td className="px-4 py-3 text-muted-foreground">
{recipe.createdAt.toLocaleDateString()}
</td>
<td className="px-4 py-3">
<Link
href={`/r/${recipe.id}`}
className="text-primary underline-offset-4 hover:underline text-xs"
target="_blank"
rel="noopener noreferrer"
>
View
</Link>
</td>
</tr>
))
)}
</tbody>
</table>
</div>
</div>
);
}
+43
View File
@@ -0,0 +1,43 @@
import type { Metadata } from "next";
import { getAllSiteSettings } from "@/lib/site-settings";
import { AdminSettingsForm } from "@/components/admin/admin-settings-form";
export const metadata: Metadata = { title: "Site Settings Admin" };
const SETTING_GROUPS = [
{
title: "AI Provider Keys",
description: "Override the environment variable API keys at runtime. Values are encrypted at rest.",
keys: ["OPENAI_API_KEY", "ANTHROPIC_API_KEY", "OPENROUTER_API_KEY"] as const,
},
{
title: "AI Configuration",
description: "Provider routing and model defaults.",
keys: ["OPENROUTER_DEFAULT_MODEL", "OLLAMA_BASE_URL"] as const,
},
{
title: "Push Notifications (VAPID)",
description: "Keys for web push notifications. Generate with: npx web-push generate-vapid-keys",
keys: ["NEXT_PUBLIC_VAPID_PUBLIC_KEY", "VAPID_PRIVATE_KEY"] as const,
},
];
export default async function AdminSettingsPage() {
const settings = await getAllSiteSettings();
return (
<div className="space-y-8">
<div>
<h1 className="text-2xl font-bold tracking-tight">Site Settings</h1>
<p className="text-muted-foreground text-sm mt-1">
Override .env values at runtime. DB values take precedence over environment variables.
Clear a value to fall back to the environment variable.
</p>
</div>
{SETTING_GROUPS.map((group) => (
<AdminSettingsForm key={group.title} group={group} settings={settings} />
))}
</div>
);
}
+131
View File
@@ -0,0 +1,131 @@
import type { Metadata } from "next";
import { db, users, recipePhotos, recipes, eq, desc, sql, count } from "@epicure/db";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { HardDrive } from "lucide-react";
export const metadata: Metadata = { title: "Storage Usage" };
export default async function AdminStoragePage() {
const [totalPhotos, recipesWithPhotos, photosByTier, topUsers] = await Promise.all([
db.select({ count: count() }).from(recipePhotos).then((r) => r[0]),
db
.select({ count: count() })
.from(recipePhotos)
.where(eq(recipePhotos.isCover, true))
.then((r) => r[0]),
db
.select({
tier: users.tier,
photoCount: sql<string>`count(${recipePhotos.id})`,
})
.from(recipePhotos)
.innerJoin(recipes, eq(recipePhotos.recipeId, recipes.id))
.innerJoin(users, eq(recipes.authorId, users.id))
.groupBy(users.tier),
db
.select({
userId: users.id,
name: users.name,
email: users.email,
tier: users.tier,
photoCount: sql<string>`count(${recipePhotos.id})`,
})
.from(recipePhotos)
.innerJoin(recipes, eq(recipePhotos.recipeId, recipes.id))
.innerJoin(users, eq(recipes.authorId, users.id))
.groupBy(users.id, users.name, users.email, users.tier)
.orderBy(desc(sql`count(${recipePhotos.id})`))
.limit(10),
]);
const freePhotos = Number(photosByTier.find((r) => r.tier === "free")?.photoCount ?? 0);
const proPhotos = Number(photosByTier.find((r) => r.tier === "pro")?.photoCount ?? 0);
return (
<div className="space-y-6">
<div>
<h1 className="text-2xl font-bold tracking-tight">Storage Usage</h1>
<p className="text-muted-foreground text-sm mt-1">
Photo storage breakdown by tier and user.
</p>
</div>
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
<Card>
<CardHeader className="flex flex-row items-center justify-between pb-2">
<CardTitle className="text-sm font-medium text-muted-foreground">Total Photos</CardTitle>
<HardDrive className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{(totalPhotos?.count ?? 0).toLocaleString()}</div>
<p className="text-xs text-muted-foreground mt-1">{recipesWithPhotos?.count ?? 0} cover photos</p>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between pb-2">
<CardTitle className="text-sm font-medium text-muted-foreground">Free Tier Photos</CardTitle>
<HardDrive className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{freePhotos.toLocaleString()}</div>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between pb-2">
<CardTitle className="text-sm font-medium text-muted-foreground">Pro Tier Photos</CardTitle>
<HardDrive className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{proPhotos.toLocaleString()}</div>
</CardContent>
</Card>
</div>
<div>
<h2 className="text-lg font-semibold mb-3">Top 10 Users by Photo Count</h2>
<div className="rounded-md border">
<table className="w-full text-sm">
<thead className="border-b bg-muted/50">
<tr>
<th className="px-4 py-3 text-left font-medium">User</th>
<th className="px-4 py-3 text-left font-medium">Tier</th>
<th className="px-4 py-3 text-right font-medium">Photos</th>
</tr>
</thead>
<tbody>
{topUsers.length === 0 ? (
<tr>
<td colSpan={3} className="px-4 py-8 text-center text-muted-foreground">
No photos uploaded yet.
</td>
</tr>
) : (
topUsers.map((row) => (
<tr key={row.userId} className="border-b last:border-0 hover:bg-muted/30">
<td className="px-4 py-3">
<div className="font-medium">{row.name ?? "Unknown"}</div>
{row.email && (
<div className="text-xs text-muted-foreground">{row.email}</div>
)}
</td>
<td className="px-4 py-3">
<Badge variant={row.tier === "pro" ? "default" : "secondary"}>
{row.tier ?? "—"}
</Badge>
</td>
<td className="px-4 py-3 text-right font-mono">
{Number(row.photoCount).toLocaleString()}
</td>
</tr>
))
)}
</tbody>
</table>
</div>
</div>
</div>
);
}
+167
View File
@@ -0,0 +1,167 @@
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { db, users, recipes, userUsage, eq, desc, count, and, sql } from "@epicure/db";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Separator } from "@/components/ui/separator";
import { UserEditor } from "@/components/admin/user-editor";
import Link from "next/link";
import { ArrowLeft } from "lucide-react";
export const metadata: Metadata = { title: "User Detail" };
interface PageProps {
params: Promise<{ id: string }>;
}
const ROLE_COLORS = {
user: "secondary",
moderator: "outline",
admin: "destructive",
} as const;
const TIER_COLORS = {
free: "secondary",
pro: "default",
} as const;
export default async function AdminUserDetailPage({ params }: PageProps) {
const { id } = await params;
const [user] = await db.select().from(users).where(eq(users.id, id)).limit(1);
if (!user) notFound();
const currentMonth = new Date().toISOString().slice(0, 7);
const [usage] = await db
.select()
.from(userUsage)
.where(and(eq(userUsage.userId, id), eq(userUsage.month, currentMonth)))
.limit(1);
const [recipeCountRow] = await db
.select({ count: count() })
.from(recipes)
.where(eq(recipes.authorId, id));
const recentRecipes = await db
.select({
id: recipes.id,
title: recipes.title,
visibility: recipes.visibility,
createdAt: recipes.createdAt,
})
.from(recipes)
.where(eq(recipes.authorId, id))
.orderBy(desc(recipes.createdAt))
.limit(10);
return (
<div className="space-y-6">
<div className="flex items-center gap-3">
<Link
href="/admin/users"
className="flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground"
>
<ArrowLeft className="h-4 w-4" />
Back to Users
</Link>
</div>
<div className="flex items-center gap-4">
<Avatar className="h-16 w-16">
<AvatarImage src={user.avatarUrl ?? ""} />
<AvatarFallback className="text-lg">
{user.name.slice(0, 2).toUpperCase()}
</AvatarFallback>
</Avatar>
<div>
<h1 className="text-2xl font-bold tracking-tight">{user.name}</h1>
<p className="text-muted-foreground">{user.email}</p>
<p className="text-xs text-muted-foreground mt-1">
Joined {user.createdAt.toLocaleDateString()}
</p>
</div>
<div className="ml-auto flex gap-2">
<Badge variant={ROLE_COLORS[user.role]}>{user.role}</Badge>
<Badge variant={TIER_COLORS[user.tier]}>{user.tier}</Badge>
</div>
</div>
<Separator />
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<Card>
<CardHeader>
<CardTitle className="text-base">Edit Role &amp; Tier</CardTitle>
</CardHeader>
<CardContent>
<UserEditor userId={user.id} currentRole={user.role} currentTier={user.tier} />
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="text-base">Usage This Month ({currentMonth})</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
<div className="flex justify-between text-sm">
<span className="text-muted-foreground">AI Calls Used</span>
<span className="font-medium">{usage?.aiCallsUsed ?? 0}</span>
</div>
<div className="flex justify-between text-sm">
<span className="text-muted-foreground">Total Recipes</span>
<span className="font-medium">{recipeCountRow?.count ?? 0}</span>
</div>
<div className="flex justify-between text-sm">
<span className="text-muted-foreground">Storage Used</span>
<span className="font-medium">{usage?.storageUsedMb ?? 0} MB</span>
</div>
</CardContent>
</Card>
</div>
<div>
<h2 className="text-lg font-semibold mb-3">Recent Recipes</h2>
{recentRecipes.length === 0 ? (
<p className="text-muted-foreground text-sm">No recipes yet.</p>
) : (
<div className="rounded-md border">
<table className="w-full text-sm">
<thead className="border-b bg-muted/50">
<tr>
<th className="px-4 py-3 text-left font-medium">Title</th>
<th className="px-4 py-3 text-left font-medium">Visibility</th>
<th className="px-4 py-3 text-left font-medium">Created</th>
<th className="px-4 py-3 text-left font-medium">Link</th>
</tr>
</thead>
<tbody>
{recentRecipes.map((recipe) => (
<tr key={recipe.id} className="border-b last:border-0 hover:bg-muted/30">
<td className="px-4 py-3 font-medium">{recipe.title}</td>
<td className="px-4 py-3">
<Badge variant="outline">{recipe.visibility}</Badge>
</td>
<td className="px-4 py-3 text-muted-foreground">
{recipe.createdAt.toLocaleDateString()}
</td>
<td className="px-4 py-3">
<Link
href={`/r/${recipe.id}`}
className="text-primary underline-offset-4 hover:underline text-xs"
>
View
</Link>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
</div>
);
}
+75
View File
@@ -0,0 +1,75 @@
import type { Metadata } from "next";
import { db } from "@epicure/db";
import { users } from "@epicure/db";
import { desc } from "@epicure/db";
import { Badge } from "@/components/ui/badge";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import Link from "next/link";
export const metadata: Metadata = { title: "User Management" };
const ROLE_COLORS = {
user: "secondary",
moderator: "outline",
admin: "destructive",
} as const;
const TIER_COLORS = {
free: "secondary",
pro: "default",
} as const;
export default async function AdminUsersPage() {
const allUsers = await db
.select()
.from(users)
.orderBy(desc(users.createdAt))
.limit(100);
return (
<div className="space-y-6">
<h1 className="text-2xl font-bold tracking-tight">Users</h1>
<div className="rounded-md border">
<table className="w-full text-sm">
<thead className="border-b bg-muted/50">
<tr>
<th className="px-4 py-3 text-left font-medium">User</th>
<th className="px-4 py-3 text-left font-medium">Role</th>
<th className="px-4 py-3 text-left font-medium">Tier</th>
<th className="px-4 py-3 text-left font-medium">Joined</th>
</tr>
</thead>
<tbody>
{allUsers.map((user) => (
<tr key={user.id} className="border-b last:border-0 hover:bg-muted/30">
<td className="px-4 py-3">
<Link href={`/admin/users/${user.id}`} className="flex items-center gap-3 group">
<Avatar className="h-8 w-8">
<AvatarImage src={user.avatarUrl ?? ""} />
<AvatarFallback className="text-xs">
{user.name.slice(0, 2).toUpperCase()}
</AvatarFallback>
</Avatar>
<div>
<div className="font-medium group-hover:underline underline-offset-4">{user.name}</div>
<div className="text-muted-foreground text-xs">{user.email}</div>
</div>
</Link>
</td>
<td className="px-4 py-3">
<Badge variant={ROLE_COLORS[user.role]}>{user.role}</Badge>
</td>
<td className="px-4 py-3">
<Badge variant={TIER_COLORS[user.tier]}>{user.tier}</Badge>
</td>
<td className="px-4 py-3 text-muted-foreground">
{user.createdAt.toLocaleDateString()}
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
);
}
@@ -0,0 +1,51 @@
import { type NextRequest, NextResponse } from "next/server";
import { headers } from "next/headers";
import { auth } from "@/lib/auth/server";
import { db, users, auditLogs, eq } from "@epicure/db";
import { setSiteSetting, type SiteSettingKey } from "@/lib/site-settings";
import { randomUUID } from "crypto";
const ALLOWED_KEYS: SiteSettingKey[] = [
"OPENAI_API_KEY",
"ANTHROPIC_API_KEY",
"OPENROUTER_API_KEY",
"OPENROUTER_DEFAULT_MODEL",
"OLLAMA_BASE_URL",
"NEXT_PUBLIC_VAPID_PUBLIC_KEY",
"VAPID_PRIVATE_KEY",
];
async function requireAdmin() {
const session = await auth.api.getSession({ headers: await headers() });
if (!session) return null;
const [dbUser] = await db.select({ role: users.role }).from(users).where(eq(users.id, session.user.id));
if (dbUser?.role !== "admin") return null;
return session;
}
export async function PUT(req: NextRequest) {
const session = await requireAdmin();
if (!session) return NextResponse.json({ error: "Forbidden" }, { status: 403 });
const body = (await req.json()) as Record<string, string | null>;
const changed: string[] = [];
for (const [key, value] of Object.entries(body)) {
if (!ALLOWED_KEYS.includes(key as SiteSettingKey)) continue;
await setSiteSetting(key as SiteSettingKey, value, session.user.id);
changed.push(key);
}
if (changed.length > 0) {
await db.insert(auditLogs).values({
id: randomUUID(),
userId: session.user.id,
action: "admin.settings.update",
targetType: "site_settings",
metadata: JSON.stringify({ keys: changed }),
createdAt: new Date(),
});
}
return NextResponse.json({ ok: true });
}
@@ -0,0 +1,26 @@
import { NextRequest, NextResponse } from "next/server";
import { requireAdmin } from "@/lib/api-auth";
import { sendEmail, verifyEmailHtml } from "@/lib/email";
export async function POST(req: NextRequest) {
const { response } = await requireAdmin();
if (response) return response;
const { to } = await req.json() as { to: string };
if (!to) return NextResponse.json({ error: "Missing 'to'" }, { status: 400 });
try {
await sendEmail({
to,
subject: "Epicure — test email",
html: verifyEmailHtml(`${process.env["BETTER_AUTH_URL"] ?? "http://localhost:3001"}/verify-email?token=test`),
});
return NextResponse.json({
ok: true,
smtp_host: process.env["SMTP_HOST"] ?? null,
smtp_user: process.env["SMTP_USER"] ?? null,
});
} catch (err) {
return NextResponse.json({ error: String(err) }, { status: 500 });
}
}
@@ -0,0 +1,56 @@
import { NextRequest, NextResponse } from "next/server";
import { requireAdmin } from "@/lib/api-auth";
import { db, users, auditLogs, eq } from "@epicure/db";
import { randomUUID } from "crypto";
interface RouteContext {
params: Promise<{ id: string }>;
}
export async function PATCH(req: NextRequest, { params }: RouteContext) {
const { session, response } = await requireAdmin();
if (response) return response;
const { id } = await params;
const body = await req.json() as { role?: string; tier?: string };
const { role, tier } = body;
const validRoles = ["user", "moderator", "admin"] as const;
const validTiers = ["free", "pro"] as const;
if (role !== undefined && !validRoles.includes(role as typeof validRoles[number])) {
return NextResponse.json({ error: "Invalid role" }, { status: 400 });
}
if (tier !== undefined && !validTiers.includes(tier as typeof validTiers[number])) {
return NextResponse.json({ error: "Invalid tier" }, { status: 400 });
}
const updateData: Partial<{ role: "user" | "moderator" | "admin"; tier: "free" | "pro"; updatedAt: Date }> = {
updatedAt: new Date(),
};
if (role) updateData.role = role as "user" | "moderator" | "admin";
if (tier) updateData.tier = tier as "free" | "pro";
const [updated] = await db
.update(users)
.set(updateData)
.where(eq(users.id, id))
.returning({ id: users.id, role: users.role, tier: users.tier });
if (!updated) {
return NextResponse.json({ error: "User not found" }, { status: 404 });
}
// Write audit log
await db.insert(auditLogs).values({
id: randomUUID(),
userId: session!.user.id,
action: "admin.user.update",
targetType: "user",
targetId: id,
metadata: JSON.stringify({ role, tier }),
createdAt: new Date(),
});
return NextResponse.json({ user: updated });
}
@@ -0,0 +1,133 @@
"use client";
import { useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import { Eye, EyeOff } from "lucide-react";
type SettingMeta = {
value: string | null;
isSecret: boolean;
fromDb: boolean;
};
type Group = {
title: string;
description: string;
keys: readonly string[];
};
export function AdminSettingsForm({
group,
settings,
}: {
group: Group;
settings: Record<string, SettingMeta>;
}) {
const [values, setValues] = useState<Record<string, string>>(() =>
Object.fromEntries(
group.keys.map((k) => [k, settings[k]?.isSecret && settings[k]?.value ? "" : (settings[k]?.value ?? "")])
)
);
const [showSecret, setShowSecret] = useState<Record<string, boolean>>({});
const [saving, setSaving] = useState(false);
async function handleSave() {
setSaving(true);
try {
const res = await fetch("/api/v1/admin/settings", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(
Object.fromEntries(group.keys.map((k) => [k, values[k] || null]))
),
});
if (!res.ok) throw new Error("Save failed");
toast.success("Settings saved");
} catch {
toast.error("Failed to save settings");
} finally {
setSaving(false);
}
}
return (
<section className="rounded-xl border p-6 space-y-4">
<div>
<h2 className="font-semibold text-lg">{group.title}</h2>
<p className="text-sm text-muted-foreground mt-1">{group.description}</p>
</div>
<div className="space-y-4">
{group.keys.map((key) => {
const meta = settings[key];
const isSecret = meta?.isSecret ?? false;
const fromDb = meta?.fromDb ?? false;
const hasValue = !!meta?.value;
const revealed = showSecret[key];
return (
<div key={key} className="space-y-1.5">
<div className="flex items-center gap-2">
<Label className="font-mono text-xs">{key}</Label>
{hasValue && (
<Badge variant={fromDb ? "default" : "secondary"} className="text-xs">
{fromDb ? "DB override" : "from .env"}
</Badge>
)}
{!hasValue && (
<Badge variant="outline" className="text-xs text-muted-foreground">
not set
</Badge>
)}
</div>
<div className="flex gap-2">
<Input
type={isSecret && !revealed ? "password" : "text"}
placeholder={
isSecret && hasValue
? "Enter new value to replace (leave blank to keep current)"
: `Enter ${key}`
}
value={values[key] ?? ""}
onChange={(e) => setValues((prev) => ({ ...prev, [key]: e.target.value }))}
className="font-mono text-sm"
/>
{isSecret && (
<Button
type="button"
variant="outline"
size="icon"
onClick={() => setShowSecret((prev) => ({ ...prev, [key]: !prev[key] }))}
>
{revealed ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
</Button>
)}
{fromDb && (
<Button
type="button"
variant="outline"
size="sm"
onClick={() => {
setValues((prev) => ({ ...prev, [key]: "" }));
}}
className="text-destructive hover:text-destructive shrink-0"
>
Clear
</Button>
)}
</div>
</div>
);
})}
</div>
<Button onClick={() => { void handleSave(); }} disabled={saving} size="sm">
{saving ? "Saving…" : "Save"}
</Button>
</section>
);
}
+82
View File
@@ -0,0 +1,82 @@
"use client";
import { useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Label } from "@/components/ui/label";
interface UserEditorProps {
userId: string;
currentRole: "user" | "moderator" | "admin";
currentTier: "free" | "pro";
}
export function UserEditor({ userId, currentRole, currentTier }: UserEditorProps) {
const [role, setRole] = useState<"user" | "moderator" | "admin">(currentRole);
const [tier, setTier] = useState<"free" | "pro">(currentTier);
const [saving, setSaving] = useState(false);
async function handleSave() {
setSaving(true);
try {
const res = await fetch(`/api/v1/admin/users/${userId}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ role, tier }),
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
throw new Error((data as { error?: string }).error ?? "Failed to save");
}
toast.success("User updated successfully");
} catch (err) {
toast.error(err instanceof Error ? err.message : "Failed to save");
} finally {
setSaving(false);
}
}
return (
<div className="flex flex-col gap-4">
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="role-select">Role</Label>
<Select value={role} onValueChange={(v) => setRole(v as typeof role)}>
<SelectTrigger id="role-select">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="user">User</SelectItem>
<SelectItem value="moderator">Moderator</SelectItem>
<SelectItem value="admin">Admin</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label htmlFor="tier-select">Tier</Label>
<Select value={tier} onValueChange={(v) => setTier(v as typeof tier)}>
<SelectTrigger id="tier-select">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="free">Free</SelectItem>
<SelectItem value="pro">Pro</SelectItem>
</SelectContent>
</Select>
</div>
</div>
<div>
<Button onClick={handleSave} disabled={saving}>
{saving ? "Saving…" : "Save Changes"}
</Button>
</div>
</div>
);
}