From 013ca67c151b51575151424084f6358522b83579 Mon Sep 17 00:00:00 2001 From: Mohamed Bassem Date: Wed, 24 Dec 2025 13:58:37 +0200 Subject: refactor: move assets to their own model (#2301) * refactor: move assets to their own model * move asset privacy checks to the model --- packages/api/routes/assets.ts | 39 ++++----------------------------------- 1 file changed, 4 insertions(+), 35 deletions(-) (limited to 'packages/api') diff --git a/packages/api/routes/assets.ts b/packages/api/routes/assets.ts index 50d11c47..e7d1c35f 100644 --- a/packages/api/routes/assets.ts +++ b/packages/api/routes/assets.ts @@ -1,11 +1,8 @@ import { zValidator } from "@hono/zod-validator"; -import { TRPCError } from "@trpc/server"; -import { eq } from "drizzle-orm"; import { Hono } from "hono"; import { z } from "zod"; -import { assets } from "@karakeep/db/schema"; -import { BareBookmark } from "@karakeep/trpc/models/bookmarks"; +import { Asset } from "@karakeep/trpc/models/assets"; import { authMiddleware } from "../middlewares/auth"; import { serveAsset } from "../utils/assets"; @@ -37,39 +34,11 @@ const app = new Hono() ) .get("/:assetId", async (c) => { const assetId = c.req.param("assetId"); - const assetDb = await c.var.ctx.db.query.assets.findFirst({ - where: eq(assets.id, assetId), - columns: { - id: true, - userId: true, - bookmarkId: true, - }, - }); - if (!assetDb) { - return c.json({ error: "Asset not found" }, { status: 404 }); - } + const asset = await Asset.fromId(c.var.ctx, assetId); + await asset.ensureCanView(); - // If asset is not attached to a bookmark yet, only owner can access it - if (!assetDb.bookmarkId) { - if (assetDb.userId !== c.var.ctx.user.id) { - return c.json({ error: "Asset not found" }, { status: 404 }); - } - return await serveAsset(c, assetId, assetDb.userId); - } - - // If asset is attached to a bookmark, check bookmark access permissions - try { - // This throws if the user doesn't have access to the bookmark - await BareBookmark.bareFromId(c.var.ctx, assetDb.bookmarkId); - } catch (e) { - if (e instanceof TRPCError && e.code === "FORBIDDEN") { - return c.json({ error: "Asset not found" }, { status: 404 }); - } - throw e; - } - - return await serveAsset(c, assetId, assetDb.userId); + return await serveAsset(c, assetId, asset.asset.userId); }); export default app; -- cgit v1.2.3-70-g09d2