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
47 lines
1.4 KiB
TypeScript
47 lines
1.4 KiB
TypeScript
import { Handlers } from "$fresh/server.ts";
|
|
import { db } from "$root/databases/db.ts";
|
|
import { students } 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";
|
|
|
|
export const handler: Handlers<null, AuthenticatedState> = {
|
|
// #7 GET /students
|
|
GET: withRules(["student_read"])(async (request, _context) => {
|
|
const url = new URL(request.url);
|
|
const idPromo = url.searchParams.get("idPromo");
|
|
|
|
const rows = idPromo
|
|
? await db.select().from(students).where(eq(students.idPromo, idPromo))
|
|
: await db.select().from(students);
|
|
|
|
return new Response(JSON.stringify(rows), {
|
|
headers: { "content-type": "application/json" },
|
|
});
|
|
}),
|
|
|
|
// #8 POST /students
|
|
POST: withRules(["student_write"])(async (request, _context) => {
|
|
const body: {
|
|
numEtud: number;
|
|
nom: string;
|
|
prenom: string;
|
|
idPromo: string;
|
|
} = await request.json();
|
|
|
|
if (!body.nom || !body.prenom || !body.idPromo) {
|
|
return new Response(null, { status: 400 });
|
|
}
|
|
|
|
const [created] = await db
|
|
.insert(students)
|
|
.values({ nom: body.nom, prenom: body.prenom, idPromo: body.idPromo })
|
|
.returning();
|
|
|
|
return new Response(JSON.stringify(created), {
|
|
status: 201,
|
|
headers: { "content-type": "application/json" },
|
|
});
|
|
}),
|
|
};
|