Compare commits

...

3 Commits

Author SHA1 Message Date
djalim 1a25ae981a feat(defaults/withRules.ts): add own_teaching_note rule for teacher access 2026-04-22 15:28:33 +02:00
djalim 996e65cfc6 feat(defaults/withRules): add permission rule wrapper 2026-04-22 15:10:29 +02:00
djalim 92182b952f feat(modules): add CRUD endpoints for module resource
Implement GET, PUT, DELETE for /modules/{idModule} with 404 handling.
2026-04-22 14:47:08 +02:00
2 changed files with 173 additions and 0 deletions
+108
View File
@@ -0,0 +1,108 @@
import { FreshContext } from "$fresh/server.ts";
import { db } from "$root/databases/db.ts";
import {
enseignements,
rolePermissions,
users,
} from "$root/databases/schema.ts";
import { AuthenticatedState } from "$root/defaults/interfaces.ts";
import { and, eq } from "npm:drizzle-orm@0.45.2";
type RuleFn = (
req: Request,
ctx: FreshContext<AuthenticatedState>,
) => Promise<boolean> | boolean;
async function hasPermission(
uid: string,
permission: string,
): Promise<boolean> {
const [user] = await db.select().from(users).where(eq(users.id, uid));
if (!user || user.idRole === null) return false;
const [rp] = await db.select().from(rolePermissions).where(
and(
eq(rolePermissions.idRole, user.idRole!),
eq(rolePermissions.idPermission, permission),
),
);
return !!rp;
}
function parseNumEtud(uid: string): number {
return parseInt(uid.slice(1));
}
const rules = {
student_read: (_req: Request, ctx: FreshContext<AuthenticatedState>) =>
hasPermission(ctx.state.session.uid, "student_read"),
student_write: (_req: Request, ctx: FreshContext<AuthenticatedState>) =>
hasPermission(ctx.state.session.uid, "student_write"),
note_read: (_req: Request, ctx: FreshContext<AuthenticatedState>) =>
hasPermission(ctx.state.session.uid, "note_read"),
note_write: (_req: Request, ctx: FreshContext<AuthenticatedState>) =>
hasPermission(ctx.state.session.uid, "note_write"),
module_read: (_req: Request, ctx: FreshContext<AuthenticatedState>) =>
hasPermission(ctx.state.session.uid, "module_read"),
module_write: (_req: Request, ctx: FreshContext<AuthenticatedState>) =>
hasPermission(ctx.state.session.uid, "module_write"),
user_read: (_req: Request, ctx: FreshContext<AuthenticatedState>) =>
hasPermission(ctx.state.session.uid, "user_read"),
user_write: (_req: Request, ctx: FreshContext<AuthenticatedState>) =>
hasPermission(ctx.state.session.uid, "user_write"),
role_write: (_req: Request, ctx: FreshContext<AuthenticatedState>) =>
hasPermission(ctx.state.session.uid, "role_write"),
// Contextual rules — student accessing their own data
own_student: (_req: Request, ctx: FreshContext<AuthenticatedState>) =>
parseNumEtud(ctx.state.session.uid) === Number(ctx.params.numEtud),
own_note: (_req: Request, ctx: FreshContext<AuthenticatedState>) =>
parseNumEtud(ctx.state.session.uid) === Number(ctx.params.numEtud),
// Contextual rule — teacher accessing notes for a module they teach
own_teaching_note: async (
_req: Request,
ctx: FreshContext<AuthenticatedState>,
) => {
const [row] = await db.select().from(enseignements).where(
and(
eq(enseignements.idProf, ctx.state.session.uid),
eq(enseignements.idModule, ctx.params.idModule),
),
);
return !!row;
},
};
export type RuleName = keyof typeof rules;
type HandlerFn = (
req: Request,
ctx: FreshContext<AuthenticatedState>,
) => Promise<Response>;
/**
* Wraps a route handler with permission checks.
* Access is granted if ANY of the provided rules passes (OR logic).
* Returns 403 if none pass.
*
* @example
* export const handler: Handlers<null, AuthenticatedState> = {
* GET: withRules(["note_read", "own_note"])(async (req, ctx) => {
* // ...
* }),
* };
*/
export function withRules(ruleNames: RuleName[]) {
return (handler: HandlerFn): HandlerFn => {
return async (req, ctx) => {
const results = await Promise.all(
ruleNames.map((name) => rules[name](req, ctx)),
);
if (!results.some(Boolean)) {
return new Response(null, { status: 403 });
}
return handler(req, ctx);
};
};
}
@@ -0,0 +1,65 @@
import { FreshContext, Handlers } from "$fresh/server.ts";
import { db } from "$root/databases/db.ts";
import { modules } from "$root/databases/schema.ts";
import { AuthenticatedState } from "$root/defaults/interfaces.ts";
import { eq } from "npm:drizzle-orm";
const NOT_FOUND = new Response(
JSON.stringify({ error: "Ressource introuvable" }),
{ status: 404, headers: { "content-type": "application/json" } },
);
export const handler: Handlers<null, AuthenticatedState> = {
// #25 GET /modules/{idModule}
async GET(
_request: Request,
context: FreshContext<AuthenticatedState>,
): Promise<Response> {
const module = await db
.select()
.from(modules)
.where(eq(modules.id, context.params.idModule))
.then((rows) => rows[0] ?? null);
if (!module) return NOT_FOUND;
return new Response(JSON.stringify(module), {
headers: { "content-type": "application/json" },
});
},
// #26 PUT /modules/{idModule}
async PUT(
request: Request,
context: FreshContext<AuthenticatedState>,
): Promise<Response> {
const body: { nom: string } = await request.json();
const [updated] = await db
.update(modules)
.set({ nom: body.nom })
.where(eq(modules.id, context.params.idModule))
.returning();
if (!updated) return NOT_FOUND;
return new Response(JSON.stringify(updated), {
headers: { "content-type": "application/json" },
});
},
// #27 DELETE /modules/{idModule}
async DELETE(
_request: Request,
context: FreshContext<AuthenticatedState>,
): Promise<Response> {
const [deleted] = await db
.delete(modules)
.where(eq(modules.id, context.params.idModule))
.returning();
if (!deleted) return NOT_FOUND;
return new Response(null, { status: 204 });
},
};