feat(posts-api): assegna autore in POST, ownership su PUT/DELETE

This commit is contained in:
2026-07-05 21:51:34 +02:00
parent 6d1e2607ee
commit c3267c9be2
4 changed files with 39 additions and 7 deletions
+11 -5
View File
@@ -1,15 +1,17 @@
import type { APIRoute } from 'astro';
import { getDb } from '../../../../lib/db';
import { getPostById, updatePost, deletePost } from '../../../../lib/posts';
import { getPostById, updatePost, deletePost, canModifyPost } from '../../../../lib/posts';
import { parsePostBody } from '../../../../lib/post-body';
export const prerender = false;
const json = (status: number, body: object) =>
new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } });
export const PUT: APIRoute = async ({ params, request }) => {
export const PUT: APIRoute = async ({ params, request, locals }) => {
const id = Number(params.id);
if (!getPostById(getDb(), id)) return json(404, { error: 'Articolo non trovato.' });
const existing = getPostById(getDb(), id);
if (!existing) return json(404, { error: 'Articolo non trovato.' });
if (!canModifyPost(locals.user!.role, locals.user!.id, existing)) return json(403, { error: 'Non puoi modificare questo articolo.' });
let data: Record<string, unknown>;
try { data = await request.json(); } catch { return json(400, { error: 'Dati non validi.' }); }
const parsed = parsePostBody(data);
@@ -23,7 +25,11 @@ export const PUT: APIRoute = async ({ params, request }) => {
}
};
export const DELETE: APIRoute = ({ params }) => {
deletePost(getDb(), Number(params.id));
export const DELETE: APIRoute = ({ params, locals }) => {
const id = Number(params.id);
const existing = getPostById(getDb(), id);
if (!existing) return json(404, { error: 'Articolo non trovato.' });
if (!canModifyPost(locals.user!.role, locals.user!.id, existing)) return json(403, { error: 'Non puoi eliminare questo articolo.' });
deletePost(getDb(), id);
return json(200, { ok: true });
};