Files
Arnaud 3e71bd29a2 security: widen API-key auth to content/AI routes (v0.27.0)
Convert requireSession -> requireSessionOrApiKey across recipes,
collections, meal-plans, shopping-lists, pantry, feed, and ai/*
(52 routes) so API keys work end-to-end, not just for the handful of
endpoints that supported them before. Scope was explicitly confirmed
per-resource-family with the user before any file was touched.

Left session-cookie-only, deliberately: users/me*, ai-keys/*,
webhooks/*, conversations/*, notifications/*, push/subscribe, admin/*
— account/credential-adjacent surface that shouldn't widen without a
separate, explicit decision.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-14 11:20:26 +02:00

61 lines
2.0 KiB
TypeScript

import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { db, pantryItems, eq, desc, sql } from "@epicure/db";
import { requireSessionOrApiKey } from "@/lib/api-auth";
const Schema = z.object({
rawName: z.string().min(1).max(200),
quantity: z.string().optional(),
unit: z.string().optional(),
expiresAt: z.string().datetime().optional(),
});
export async function GET(req: NextRequest) {
const { session, response } = await requireSessionOrApiKey(req);
if (response) return response;
const { searchParams } = req.nextUrl;
const limitRaw = parseInt(searchParams.get("limit") ?? "50");
const limit = Math.min(Number.isNaN(limitRaw) ? 50 : Math.max(1, limitRaw), 100);
const offsetRaw = parseInt(searchParams.get("offset") ?? "0");
const offset = Number.isNaN(offsetRaw) ? 0 : Math.max(0, offsetRaw);
const [items, totalRow] = await Promise.all([
db.query.pantryItems.findMany({
where: eq(pantryItems.userId, session!.user.id),
orderBy: desc(pantryItems.createdAt),
limit,
offset,
}),
db
.select({ total: sql<number>`count(*)::int` })
.from(pantryItems)
.where(eq(pantryItems.userId, session!.user.id)),
]);
const total = totalRow[0]?.total ?? 0;
return NextResponse.json({ data: items, total, limit, offset });
}
export async function POST(req: NextRequest) {
const { session, response } = await requireSessionOrApiKey(req);
if (response) return response;
const body = await req.json() as unknown;
const parsed = Schema.safeParse(body);
if (!parsed.success) return NextResponse.json({ error: "Validation error" }, { status: 400 });
const id = crypto.randomUUID();
await db.insert(pantryItems).values({
id,
userId: session!.user.id,
rawName: parsed.data.rawName,
quantity: parsed.data.quantity,
unit: parsed.data.unit,
expiresAt: parsed.data.expiresAt ? new Date(parsed.data.expiresAt) : undefined,
});
return NextResponse.json({ id }, { status: 201 });
}