File sharing
This commit is contained in:
@@ -0,0 +1,62 @@
|
||||
import { z } from "@zod/zod";
|
||||
|
||||
import { define } from "@/utils.ts";
|
||||
import { authenticate, unauthorized } from "@/src/auth.ts";
|
||||
import { db, type FileRow, type ShareRow } from "@/src/db.ts";
|
||||
import type { ShareEntry } from "@/src/files.ts";
|
||||
|
||||
const ShareBody = z.object({
|
||||
metadata: z.base64().min(1).max(4096),
|
||||
secret: z.base64().min(1).max(200),
|
||||
});
|
||||
|
||||
const not_found = () => Response.json({ error: "File not found" }, { status: 404 });
|
||||
|
||||
export const handler = define.handlers({
|
||||
// The body only has encrypted data, the link secret itself never reaches the server
|
||||
async POST(ctx) {
|
||||
const user = await authenticate(ctx.req);
|
||||
if (!user) {
|
||||
return unauthorized();
|
||||
}
|
||||
|
||||
const body = ShareBody.safeParse(await ctx.req.json().catch(() => null));
|
||||
if (!body.success) {
|
||||
return Response.json({ error: "Invalid request" }, { status: 400 });
|
||||
}
|
||||
|
||||
const file = await db.get_entry("files", ctx.params.id) as FileRow | undefined;
|
||||
if (!file || file.user_id !== user.id) {
|
||||
return not_found();
|
||||
}
|
||||
if (await db.get_entry_by_index("shares", "file_id", file.id)) {
|
||||
return Response.json({ error: "This file is already shared" }, { status: 409 });
|
||||
}
|
||||
|
||||
const share = await db.create_entry("shares", {
|
||||
user_id: user.id,
|
||||
file_id: file.id,
|
||||
metadata: body.data.metadata,
|
||||
secret: body.data.secret,
|
||||
});
|
||||
return Response.json({ id: share.id, secret: share.secret } satisfies ShareEntry, { status: 201 });
|
||||
},
|
||||
|
||||
async DELETE(ctx) {
|
||||
const user = await authenticate(ctx.req);
|
||||
if (!user) {
|
||||
return unauthorized();
|
||||
}
|
||||
|
||||
const file = await db.get_entry("files", ctx.params.id) as FileRow | undefined;
|
||||
if (!file || file.user_id !== user.id) {
|
||||
return not_found();
|
||||
}
|
||||
|
||||
const shares = await db.get_entries_by_index("shares", "file_id", file.id) as ShareRow[];
|
||||
for (const share of shares) {
|
||||
await db.delete_entry("shares", share);
|
||||
}
|
||||
return new Response(null, { status: 204 });
|
||||
},
|
||||
});
|
||||
Reference in New Issue
Block a user