All files / src/server/api item-photo-file.ts

88.23% Statements 15/17
91.66% Branches 11/12
100% Functions 1/1
87.5% Lines 14/16

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61                                    11x 11x 1x     10x   10x 10x           10x 10x   4x 4x       4x 4x 1x     3x                              
import { NextResponse, type NextRequest } from "next/server";
import { getSession } from "@/lib/auth";
import { getDb } from "@/lib/db";
import { servePhotoFile } from "@/lib/photo-serving";
import { ItemController } from "@/server/api/items";
import { PhotoController } from "@/server/api/photos";
import { requireApiCapability } from "@/server/dal/collection-access";
 
export interface ItemPhotoFileParams {
  id: string;
  itemId: string;
  photoId: string;
}
 
export async function serveItemPhotoFile(
  request: NextRequest,
  params: Promise<ItemPhotoFileParams>,
) {
  const session = await getSession();
  if (!session?.user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }
 
  const db = getDb();
 
  try {
    const { id, itemId, photoId } = await params;
    // Authz BEFORE existence (purses-ct0): the collection is known from the URL, so a
    // caller with no access is turned away without ever learning whether the item or
    // photo exists. Resolving first would leak that (404 "not here" vs 403 "here, but
    // not yours") — an existence oracle for a non-member.
    // items:read = curator — any curator may view photo files (full-curator model).
    const access = await requireApiCapability(db, id, session.user.id, "items:read");
    if (access instanceof NextResponse) return access;
 
    const item = await ItemController.fromDb(db).getItem(itemId);
    Iif (!item || item.collectionId !== id) {
      return NextResponse.json({ error: "Not found" }, { status: 404 });
    }
 
    const photo = await PhotoController.fromDb(db).findById(photoId);
    if (!photo || photo.itemId !== itemId) {
      return NextResponse.json({ error: "Not found" }, { status: 404 });
    }
 
    return servePhotoFile(
      {
        blobKey: photo.blobKey,
        mimeType: photo.mimeType,
        photoId: photo.id,
        collectionId: id,
        updatedAt: photo.updatedAt,
        rotation: photo.rotation,
      },
      request,
    );
  } catch {
    return NextResponse.json({ error: "Photo fetch failed" }, { status: 500 });
  }
}