9368e68622
refactor: add withRules wrapper to API routes Use withRules to enforce permissions instead of manual checks. Remove FORBIDDEN constant, simplify handlers, import withRules, adjust GET/POST/PUT/DELETE handlers. Centralizes auth logic. refactor: replace manual auth checks with withRules wrapper for routes refactor(student routes): replace manual employee checks with withRules wrapper
73 lines
2.0 KiB
TypeScript
73 lines
2.0 KiB
TypeScript
import { FreshContext, Handlers } from "$fresh/server.ts";
|
|
import { db } from "$root/databases/db.ts";
|
|
import { promotions } from "$root/databases/schema.ts";
|
|
import { AuthenticatedState } from "$root/defaults/interfaces.ts";
|
|
import { withRules } from "$root/defaults/withRules.ts";
|
|
import { eq } from "npm:drizzle-orm@0.45.2";
|
|
|
|
const NOT_FOUND = new Response(
|
|
JSON.stringify({ error: "Ressource introuvable" }),
|
|
{ status: 404, headers: { "content-type": "application/json" } },
|
|
);
|
|
|
|
export const handler: Handlers<null, AuthenticatedState> = {
|
|
// #15 GET /promotions/{idPromo}
|
|
GET: withRules(["student_read"])(async (_request, context) => {
|
|
const promo = await db
|
|
.select()
|
|
.from(promotions)
|
|
.where(
|
|
eq(
|
|
promotions.id,
|
|
(context as FreshContext<AuthenticatedState>).params.idPromo,
|
|
),
|
|
)
|
|
.then((rows) => rows[0] ?? null);
|
|
|
|
if (!promo) return NOT_FOUND;
|
|
|
|
return new Response(JSON.stringify(promo), {
|
|
headers: { "content-type": "application/json" },
|
|
});
|
|
}),
|
|
|
|
// #16 PUT /promotions/{idPromo}
|
|
PUT: withRules(["student_write"])(async (request, context) => {
|
|
const body: { annee: string } = await request.json();
|
|
|
|
const [updated] = await db
|
|
.update(promotions)
|
|
.set({ annee: body.annee })
|
|
.where(
|
|
eq(
|
|
promotions.id,
|
|
(context as FreshContext<AuthenticatedState>).params.idPromo,
|
|
),
|
|
)
|
|
.returning();
|
|
|
|
if (!updated) return NOT_FOUND;
|
|
|
|
return new Response(JSON.stringify(updated), {
|
|
headers: { "content-type": "application/json" },
|
|
});
|
|
}),
|
|
|
|
// #17 DELETE /promotions/{idPromo}
|
|
DELETE: withRules(["student_write"])(async (_request, context) => {
|
|
const [deleted] = await db
|
|
.delete(promotions)
|
|
.where(
|
|
eq(
|
|
promotions.id,
|
|
(context as FreshContext<AuthenticatedState>).params.idPromo,
|
|
),
|
|
)
|
|
.returning();
|
|
|
|
if (!deleted) return NOT_FOUND;
|
|
|
|
return new Response(null, { status: 204 });
|
|
}),
|
|
};
|