From 1b68d825654490c008fba1da898392d9ab6ff8a8 Mon Sep 17 00:00:00 2001 From: Oliver Bryan <04oliverbryan@gmail.com> Date: Mon, 29 Dec 2025 04:44:37 +0000 Subject: [PATCH] updated /organisation/create route. creates member and ensures no duplicated slugs --- .../backend/src/routes/organisation/create.ts | 36 +++++++++++++------ 1 file changed, 25 insertions(+), 11 deletions(-) diff --git a/packages/backend/src/routes/organisation/create.ts b/packages/backend/src/routes/organisation/create.ts index 4882f9f..048424d 100644 --- a/packages/backend/src/routes/organisation/create.ts +++ b/packages/backend/src/routes/organisation/create.ts @@ -1,23 +1,37 @@ -import type { BunRequest } from "bun"; -import { createOrganisation } from "../../db/queries"; +import type { AuthedRequest } from "../../auth/middleware"; +import { createOrganisationWithOwner, getOrganisationBySlug } from "../../db/queries"; -// /organisation/create?name=Org%20Name&slug=org-name&description=Optional%20description -export default async function organisationCreate(req: BunRequest) { +// /organisation/create?name=Org%20Name&slug=org-name&userId=1&description=Optional%20description +export default async function organisationCreate(req: AuthedRequest) { const url = new URL(req.url); const name = url.searchParams.get("name"); const slug = url.searchParams.get("slug"); + const userId = url.searchParams.get("userId"); const description = url.searchParams.get("description") || undefined; - if (!name || !slug) { - return new Response(`missing parameters: ${!name ? "name " : ""}${!slug ? "slug" : ""}`, { - status: 400, - }); + if (!name || !slug || !userId) { + return new Response( + `missing parameters: ${!name ? "name " : ""}${!slug ? "slug " : ""}${!userId ? "userId" : ""}`, + { status: 400 }, + ); } - // Check if organisation with slug already exists - // TODO: Add this check when we have a getOrganisationBySlug function + const userIdNumber = Number(userId); + if (!Number.isInteger(userIdNumber)) { + return new Response("userId must be an integer", { status: 400 }); + } - const organisation = await createOrganisation(name, slug, description); + // users can only create organisations for themselves (userId cannot be spoofed) + if (req.userId !== userIdNumber) { + return new Response("access denied: you can only create organisations for yourself", { status: 403 }); + } + + const existingOrganisation = await getOrganisationBySlug(slug); + if (existingOrganisation) { + return new Response(`organisation with slug "${slug}" already exists`, { status: 409 }); + } + + const organisation = await createOrganisationWithOwner(name, slug, userIdNumber, description); return Response.json(organisation); }