🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat: add new organization routes (#6430)
Steffen Schmitzfc84da9508fd
diff --git a/fern/apis/organizations/definition/api.yml b/fern/apis/organizations/definition/api.ymlnew file mode 100644index 0000000000..2c86d7fb1a--- /dev/null+++ b/fern/apis/organizations/definition/api.yml@@ -0,0 +1,27 @@+name: langfuse+docs: |+ ## General Notes++ This admin API is only available on self-hosted instances, not on Langfuse Cloud.+ An administrator must set the `ADMIN_API_KEY` environment variable to use this API.++ ## Authentication++ Authenticate with the API by setting the Authorization header to `Bearer $ADMIN_API_KEY` where+ `$ADMIN_API_KEY` is the API key set via the container environment.++ ## Exports++ - OpenAPI spec: https://cloud.langfuse.com/generated/organizations-api/openapi.yml+ - Postman collection: https://cloud.langfuse.com/generated/organizations-postman/collection.json++error-discrimination:+ strategy: status-code+auth: bearer+imports:+ commons: commons.yml+errors:+ - commons.Error+ - commons.UnauthorizedError+ - commons.AccessDeniedError+ - commons.MethodNotAllowedErrordiff --git a/fern/apis/organizations/definition/commons.yml b/fern/apis/organizations/definition/commons.ymlnew file mode 100644index 0000000000..98fc49843f--- /dev/null+++ b/fern/apis/organizations/definition/commons.yml@@ -0,0 +1,13 @@+errors:+ Error:+ status-code: 400+ type: string+ UnauthorizedError:+ status-code: 401+ type: string+ AccessDeniedError:+ status-code: 403+ type: string+ MethodNotAllowedError:+ status-code: 405+ type: stringdiff --git a/fern/apis/organizations/definition/organizations.yml b/fern/apis/organizations/definition/organizations.ymlnew file mode 100644index 0000000000..8255402a5e--- /dev/null+++ b/fern/apis/organizations/definition/organizations.yml@@ -0,0 +1,90 @@+# yaml-language-server: $schema=https://raw.githubusercontent.com/fern-api/fern/main/fern.schema.json+imports:+ commons: ./commons.yml++service:+ auth: true+ base-path: /api/admin+ endpoints:+ getAll:+ docs: Get all organizations+ method: GET+ path: /organizations+ response: Organizations+ errors:+ - commons.UnauthorizedError+ - commons.MethodNotAllowedError++ create:+ docs: Create a new organization+ method: POST+ path: /organizations+ request:+ name: CreateOrganizationRequest+ body:+ properties:+ name: string+ response: Organization+ errors:+ - commons.Error+ - commons.UnauthorizedError+ - commons.MethodNotAllowedError++ getById:+ docs: Get organization by ID+ method: GET+ path: /organizations/{organizationId}+ path-parameters:+ organizationId: string+ response: Organization+ errors:+ - commons.Error+ - commons.UnauthorizedError+ - commons.MethodNotAllowedError++ update:+ docs: Update an organization+ method: PUT+ path: /organizations/{organizationId}+ path-parameters:+ organizationId: string+ request:+ name: UpdateOrganizationRequest+ body:+ properties:+ name: string+ response: Organization+ errors:+ - commons.Error+ - commons.UnauthorizedError+ - commons.MethodNotAllowedError++ delete:+ docs: Delete an organization+ method: DELETE+ path: /organizations/{organizationId}+ path-parameters:+ organizationId: string+ response: DeleteOrganizationResponse+ errors:+ - commons.Error+ - commons.UnauthorizedError+ - commons.MethodNotAllowedError++types:+ Organizations:+ docs: List of organizations+ properties:+ organizations: list<Organization>++ Organization:+ docs: Organization object+ properties:+ id: string+ name: string+ createdAt: datetime++ DeleteOrganizationResponse:+ docs: Response for successful organization deletion+ properties:+ success: booleandiff --git a/fern/apis/organizations/generators.yml b/fern/apis/organizations/generators.ymlnew file mode 100644index 0000000000..c85aff2983--- /dev/null+++ b/fern/apis/organizations/generators.yml@@ -0,0 +1,17 @@+default-group: local+groups:+ local:+ generators:+ - name: fernapi/fern-openapi+ version: 0.1.7+ output:+ location: local-file-system+ path: ../../../web/public/generated/organizations-api+ config:+ namespaceExport: Langfuse+ allowCustomFetcher: true+ - name: fernapi/fern-postman+ version: 0.0.45+ output:+ location: local-file-system+ path: ../../../web/public/generated/organizations-postmandiff --git a/web/public/generated/organizations-api/openapi.yml b/web/public/generated/organizations-api/openapi.ymlnew file mode 100644index 0000000000..a17d5cd386--- /dev/null+++ b/web/public/generated/organizations-api/openapi.yml@@ -0,0 +1,305 @@+openapi: 3.0.1+info:+ title: langfuse+ version: ''+ description: >-+ ## General Notes+++ This admin API is only available on self-hosted instances, not on Langfuse+ Cloud.++ An administrator must set the `ADMIN_API_KEY` environment variable to use+ this API.+++ ## Authentication+++ Authenticate with the API by setting the Authorization header to `Bearer+ $ADMIN_API_KEY` where++ `$ADMIN_API_KEY` is the API key set via the container environment.+++ ## Exports+++ - OpenAPI spec:+ https://cloud.langfuse.com/generated/organizations-api/openapi.yml++ - Postman collection:+ https://cloud.langfuse.com/generated/organizations-postman/collection.json+paths:+ /api/admin/organizations:+ get:+ description: Get all organizations+ operationId: organizations_getAll+ tags:+ - Organizations+ parameters: []+ responses:+ '200':+ description: ''+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/Organizations'+ '400':+ description: ''+ content:+ application/json:+ schema:+ type: string+ '401':+ description: ''+ content:+ application/json:+ schema:+ type: string+ '403':+ description: ''+ content:+ application/json:+ schema:+ type: string+ '405':+ description: ''+ content:+ application/json:+ schema:+ type: string+ security: &ref_0+ - BearerAuth: []+ post:+ description: Create a new organization+ operationId: organizations_create+ tags:+ - Organizations+ parameters: []+ responses:+ '200':+ description: ''+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/Organization'+ '400':+ description: ''+ content:+ application/json:+ schema:+ type: string+ '401':+ description: ''+ content:+ application/json:+ schema:+ type: string+ '403':+ description: ''+ content:+ application/json:+ schema:+ type: string+ '405':+ description: ''+ content:+ application/json:+ schema:+ type: string+ security: *ref_0+ requestBody:+ required: true+ content:+ application/json:+ schema:+ type: object+ properties:+ name:+ type: string+ required:+ - name+ /api/admin/organizations/{organizationId}:+ get:+ description: Get organization by ID+ operationId: organizations_getById+ tags:+ - Organizations+ parameters:+ - name: organizationId+ in: path+ required: true+ schema:+ type: string+ responses:+ '200':+ description: ''+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/Organization'+ '400':+ description: ''+ content:+ application/json:+ schema:+ type: string+ '401':+ description: ''+ content:+ application/json:+ schema:+ type: string+ '403':+ description: ''+ content:+ application/json:+ schema:+ type: string+ '405':+ description: ''+ content:+ application/json:+ schema:+ type: string+ security: *ref_0+ put:+ description: Update an organization+ operationId: organizations_update+ tags:+ - Organizations+ parameters:+ - name: organizationId+ in: path+ required: true+ schema:+ type: string+ responses:+ '200':+ description: ''+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/Organization'+ '400':+ description: ''+ content:+ application/json:+ schema:+ type: string+ '401':+ description: ''+ content:+ application/json:+ schema:+ type: string+ '403':+ description: ''+ content:+ application/json:+ schema:+ type: string+ '405':+ description: ''+ content:+ application/json:+ schema:+ type: string+ security: *ref_0+ requestBody:+ required: true+ content:+ application/json:+ schema:+ type: object+ properties:+ name:+ type: string+ required:+ - name+ delete:+ description: Delete an organization+ operationId: organizations_delete+ tags:+ - Organizations+ parameters:+ - name: organizationId+ in: path+ required: true+ schema:+ type: string+ responses:+ '200':+ description: ''+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/DeleteOrganizationResponse'+ '400':+ description: ''+ content:+ application/json:+ schema:+ type: string+ '401':+ description: ''+ content:+ application/json:+ schema:+ type: string+ '403':+ description: ''+ content:+ application/json:+ schema:+ type: string+ '405':+ description: ''+ content:+ application/json:+ schema:+ type: string+ security: *ref_0+components:+ schemas:+ Organizations:+ title: Organizations+ type: object+ description: List of organizations+ properties:+ organizations:+ type: array+ items:+ $ref: '#/components/schemas/Organization'+ required:+ - organizations+ Organization:+ title: Organization+ type: object+ description: Organization object+ properties:+ id:+ type: string+ name:+ type: string+ createdAt:+ type: string+ format: date-time+ required:+ - id+ - name+ - createdAt+ DeleteOrganizationResponse:+ title: DeleteOrganizationResponse+ type: object+ description: Response for successful organization deletion+ properties:+ success:+ type: boolean+ required:+ - success+ securitySchemes:+ BearerAuth:+ type: http+ scheme: bearerdiff --git a/web/public/generated/organizations-postman/collection.json b/web/public/generated/organizations-postman/collection.jsonnew file mode 100644index 0000000000..d54763e96b--- /dev/null+++ b/web/public/generated/organizations-postman/collection.json@@ -0,0 +1,200 @@+{+ "info": {+ "name": "Langfuse",+ "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json",+ "description": "## General Notes\n\nThis admin API is only available on self-hosted instances, not on Langfuse Cloud.\nAn administrator must set the `ADMIN_API_KEY` environment variable to use this API.\n\n## Authentication\n\nAuthenticate with the API by setting the Authorization header to `Bearer $ADMIN_API_KEY` where\n`$ADMIN_API_KEY` is the API key set via the container environment.\n\n## Exports\n\n- OpenAPI spec: https://cloud.langfuse.com/generated/organizations-api/openapi.yml\n- Postman collection: https://cloud.langfuse.com/generated/organizations-postman/collection.json"+ },+ "variable": [+ {+ "key": "baseUrl",+ "value": "",+ "type": "string"+ },+ {+ "key": "token",+ "value": "",+ "type": "string"+ }+ ],+ "auth": {+ "type": "bearer",+ "bearer": [+ {+ "key": "token",+ "value": "{{token}}",+ "type": "string"+ }+ ]+ },+ "item": [+ {+ "_type": "container",+ "description": null,+ "name": "Organizations",+ "item": [+ {+ "_type": "endpoint",+ "name": "Get All",+ "request": {+ "description": "Get all organizations",+ "url": {+ "raw": "{{baseUrl}}/api/admin/organizations",+ "host": [+ "{{baseUrl}}"+ ],+ "path": [+ "api",+ "admin",+ "organizations"+ ],+ "query": [],+ "variable": []+ },+ "header": [],+ "method": "GET",+ "auth": null,+ "body": null+ },+ "response": []+ },+ {+ "_type": "endpoint",+ "name": "Create",+ "request": {+ "description": "Create a new organization",+ "url": {+ "raw": "{{baseUrl}}/api/admin/organizations",+ "host": [+ "{{baseUrl}}"+ ],+ "path": [+ "api",+ "admin",+ "organizations"+ ],+ "query": [],+ "variable": []+ },+ "header": [],+ "method": "POST",+ "auth": null,+ "body": {+ "mode": "raw",+ "raw": "{\n \"name\": \"example\"\n}",+ "options": {+ "raw": {+ "language": "json"+ }+ }+ }+ },+ "response": []+ },+ {+ "_type": "endpoint",+ "name": "Get By Id",+ "request": {+ "description": "Get organization by ID",+ "url": {+ "raw": "{{baseUrl}}/api/admin/organizations/:organizationId",+ "host": [+ "{{baseUrl}}"+ ],+ "path": [+ "api",+ "admin",+ "organizations",+ ":organizationId"+ ],+ "query": [],+ "variable": [+ {+ "key": "organizationId",+ "value": "",+ "description": null+ }+ ]+ },+ "header": [],+ "method": "GET",+ "auth": null,+ "body": null+ },+ "response": []+ },+ {+ "_type": "endpoint",+ "name": "Update",+ "request": {+ "description": "Update an organization",+ "url": {+ "raw": "{{baseUrl}}/api/admin/organizations/:organizationId",+ "host": [+ "{{baseUrl}}"+ ],+ "path": [+ "api",+ "admin",+ "organizations",+ ":organizationId"+ ],+ "query": [],+ "variable": [+ {+ "key": "organizationId",+ "value": "",+ "description": null+ }+ ]+ },+ "header": [],+ "method": "PUT",+ "auth": null,+ "body": {+ "mode": "raw",+ "raw": "{\n \"name\": \"example\"\n}",+ "options": {+ "raw": {+ "language": "json"+ }+ }+ }+ },+ "response": []+ },+ {+ "_type": "endpoint",+ "name": "Delete",+ "request": {+ "description": "Delete an organization",+ "url": {+ "raw": "{{baseUrl}}/api/admin/organizations/:organizationId",+ "host": [+ "{{baseUrl}}"+ ],+ "path": [+ "api",+ "admin",+ "organizations",+ ":organizationId"+ ],+ "query": [],+ "variable": [+ {+ "key": "organizationId",+ "value": "",+ "description": null+ }+ ]+ },+ "header": [],+ "method": "DELETE",+ "auth": null,+ "body": null+ },+ "response": []+ }+ ]+ }+ ]+}\ No newline at end of filediff --git a/web/src/__tests__/async/organizations-api.servertest.ts b/web/src/__tests__/async/organizations-api.servertest.tsindex 5c11768347..a3560a4d05 100644--- a/web/src/__tests__/async/organizations-api.servertest.ts+++ b/web/src/__tests__/async/organizations-api.servertest.ts@@ -15,6 +15,16 @@ const OrganizationResponseSchema = z.object({createdAt: z.string().datetime(),});+// Schema for multiple organizations response+const OrganizationsListSchema = z.object({+ organizations: z.array(OrganizationResponseSchema),+});++// Schema for delete response+const DeleteResponseSchema = z.object({+ success: z.boolean(),+});+describe("Admin Organizations API", () => {const ADMIN_API_KEY = process.env.ADMIN_API_KEY;@@ -98,16 +108,314 @@ describe("Admin Organizations API", () => {expect(result.status).toBe(400);expect(result.body.error).toContain("Invalid request body");});+ });- it("should return 405 for non-POST methods", async () => {- const result = await makeAPICall(+ describe("GET /api/admin/organizations", () => {+ let testOrgId: string;++ beforeAll(async () => {+ // Create a test organization to retrieve+ const uniqueOrgName = `Test Org ${randomUUID().substring(0, 8)}`;+ const org = await prisma.organization.create({+ data: { name: uniqueOrgName },+ });+ testOrgId = org.id;+ });++ afterAll(async () => {+ // Clean up test organization+ await prisma.organization+ .delete({+ where: { id: testOrgId },+ })+ .catch(() => {+ /* ignore if already deleted */+ });+ });++ it("should get all organizations with valid admin authentication", async () => {+ const response = await makeZodVerifiedAPICall(+ OrganizationsListSchema,"GET","/api/admin/organizations",undefined,`Bearer ${ADMIN_API_KEY}`,+ 200,+ );++ expect(response.status).toBe(200);+ expect(Array.isArray(response.body.organizations)).toBe(true);+ expect(response.body.organizations.length).toBeGreaterThan(0);+ // Verify the test organization is in the list+ expect(+ response.body.organizations.some((org) => org.id === testOrgId),+ ).toBe(true);+ });++ it("should return 401 when no authorization header is provided", async () => {+ const result = await makeAPICall("GET", "/api/admin/organizations");+ expect(result.status).toBe(401);+ expect(result.body.error).toContain("Unauthorized");+ });+ });++ describe("GET /api/admin/organizations/[organizationId]", () => {+ let testOrgId: string;++ beforeAll(async () => {+ // Create a test organization to retrieve+ const uniqueOrgName = `Test Org ${randomUUID().substring(0, 8)}`;+ const org = await prisma.organization.create({+ data: { name: uniqueOrgName },+ });+ testOrgId = org.id;+ });++ afterAll(async () => {+ // Clean up test organization+ await prisma.organization+ .delete({+ where: { id: testOrgId },+ })+ .catch(() => {+ /* ignore if already deleted */+ });+ });++ it("should get a specific organization by ID", async () => {+ const response = await makeZodVerifiedAPICall(+ OrganizationResponseSchema,+ "GET",+ `/api/admin/organizations/${testOrgId}`,+ undefined,+ `Bearer ${ADMIN_API_KEY}`,+ 200,+ );++ expect(response.status).toBe(200);+ expect(response.body.id).toBe(testOrgId);+ });++ it("should return 404 when getting a non-existent organization", async () => {+ const nonExistentId = randomUUID();+ const result = await makeAPICall(+ "GET",+ `/api/admin/organizations/${nonExistentId}`,+ undefined,+ `Bearer ${ADMIN_API_KEY}`,+ );++ expect(result.status).toBe(404);+ expect(result.body.error).toContain("Organization not found");+ });+ });++ describe("PUT /api/admin/organizations/[organizationId]", () => {+ let testOrgId: string;++ beforeEach(async () => {+ // Create a test organization to update+ const uniqueOrgName = `Test Org ${randomUUID().substring(0, 8)}`;+ const org = await prisma.organization.create({+ data: { name: uniqueOrgName },+ });+ testOrgId = org.id;+ });++ afterEach(async () => {+ // Clean up test organization+ await prisma.organization+ .delete({+ where: { id: testOrgId },+ })+ .catch(() => {+ /* ignore if already deleted */+ });+ });++ it("should update an organization with valid admin authentication", async () => {+ const newName = `Updated Org ${randomUUID().substring(0, 8)}`;++ const response = await makeZodVerifiedAPICall(+ OrganizationResponseSchema,+ "PUT",+ `/api/admin/organizations/${testOrgId}`,+ {+ name: newName,+ },+ `Bearer ${ADMIN_API_KEY}`,+ 200,);- expect(result.status).toBe(405);- expect(result.body.error).toContain("Method Not Allowed");++ expect(response.status).toBe(200);+ expect(response.body).toMatchObject({+ id: testOrgId,+ name: newName,+ });++ // Verify the organization was actually updated in the database+ const org = await prisma.organization.findUnique({+ where: { id: testOrgId },+ });+ expect(org).not.toBeNull();+ expect(org?.name).toBe(newName);});++ it("should return 404 when updating a non-existent organization", async () => {+ const nonExistentId = randomUUID();+ const result = await makeAPICall(+ "PUT",+ `/api/admin/organizations/${nonExistentId}`,+ {+ name: "New Name",+ },+ `Bearer ${ADMIN_API_KEY}`,+ );++ expect(result.status).toBe(404);+ expect(result.body.error).toContain("Organization not found");+ });++ it("should return 400 when updating with invalid name", async () => {+ const result = await makeAPICall(+ "PUT",+ `/api/admin/organizations/${testOrgId}`,+ {+ name: "A", // Short name+ },+ `Bearer ${ADMIN_API_KEY}`,+ );++ expect(result.status).toBe(400);+ expect(result.body.error).toContain("Invalid request body");+ });++ it("should return 401 when no authorization header is provided", async () => {+ const result = await makeAPICall(+ "PUT",+ `/api/admin/organizations/${testOrgId}`,+ {+ name: "New Name",+ },+ );++ expect(result.status).toBe(401);+ expect(result.body.error).toContain("Unauthorized");+ });+ });++ describe("DELETE /api/admin/organizations/[organizationId]", () => {+ let testOrgId: string;++ beforeEach(async () => {+ // Create a test organization to delete+ const uniqueOrgName = `Test Org ${randomUUID().substring(0, 8)}`;+ const org = await prisma.organization.create({+ data: { name: uniqueOrgName },+ });+ testOrgId = org.id;+ });++ afterEach(async () => {+ // Clean up test organization if not deleted by test+ await prisma.organization+ .delete({+ where: { id: testOrgId },+ })+ .catch(() => {+ /* ignore if already deleted */+ });+ });++ it("should delete an organization with valid admin authentication", async () => {+ // Create a test organization to delete+ const uniqueOrgName = `Test Org ${randomUUID().substring(0, 8)}`;+ const orgId = (+ await prisma.organization.create({+ data: { name: uniqueOrgName },+ })+ ).id;++ const response = await makeZodVerifiedAPICall(+ DeleteResponseSchema,+ "DELETE",+ `/api/admin/organizations/${orgId}`,+ undefined,+ `Bearer ${ADMIN_API_KEY}`,+ 200,+ );++ expect(response.status).toBe(200);+ expect(response.body).toMatchObject({+ success: true,+ });++ // Verify the organization was actually deleted from the database+ const org = await prisma.organization.findUnique({+ where: { id: orgId },+ });+ expect(org).toBeNull();+ });++ it("should return 404 when deleting a non-existent organization", async () => {+ const nonExistentId = randomUUID();+ const result = await makeAPICall(+ "DELETE",+ `/api/admin/organizations/${nonExistentId}`,+ undefined,+ `Bearer ${ADMIN_API_KEY}`,+ );++ expect(result.status).toBe(404);+ expect(result.body.error).toContain("Organization not found");+ });++ it("should return 400 when organization has projects", async () => {+ // Create a project for the test organization+ await prisma.project.create({+ data: {+ name: "Test Project",+ orgId: testOrgId,+ },+ });++ const result = await makeAPICall(+ "DELETE",+ `/api/admin/organizations/${testOrgId}`,+ undefined,+ `Bearer ${ADMIN_API_KEY}`,+ );++ expect(result.status).toBe(400);+ expect(result.body.error).toContain(+ "Cannot delete organization with existing projects",+ );++ // Clean up the project+ await prisma.project.deleteMany({+ where: { orgId: testOrgId },+ });+ });++ it("should return 401 when no authorization header is provided", async () => {+ const result = await makeAPICall(+ "DELETE",+ `/api/admin/organizations/${testOrgId}`,+ );++ expect(result.status).toBe(401);+ expect(result.body.error).toContain("Unauthorized");+ });+ });++ it("should return 405 for non-supported methods", async () => {+ const result = await makeAPICall(+ "PATCH",+ "/api/admin/organizations",+ undefined,+ `Bearer ${ADMIN_API_KEY}`,+ );+ expect(result.status).toBe(405);+ expect(result.body.error).toContain("Method Not Allowed");});});diff --git a/web/src/pages/api/admin/organizations/[organizationId].ts b/web/src/pages/api/admin/organizations/[organizationId].tsnew file mode 100644index 0000000000..56ff2a2649--- /dev/null+++ b/web/src/pages/api/admin/organizations/[organizationId].ts@@ -0,0 +1,170 @@+import { type NextApiRequest, type NextApiResponse } from "next";+import { prisma } from "@langfuse/shared/src/db";+import { logger } from "@langfuse/shared/src/server";+import { AdminApiAuthService } from "@/src/features/admin-api/server/adminApiAuth";+import { organizationNameSchema } from "@/src/features/organizations/utils/organizationNameSchema";+import { auditLog } from "@/src/features/audit-logs/auditLog";+import { z } from "zod";++const validateQueryAndExtractId = (query: unknown): string | null => {+ const inputQuerySchema = z.object({+ organizationId: z.string(),+ });+ const validation = inputQuerySchema.safeParse(query);+ if (!validation.success) {+ return null;+ }+ return validation.data.organizationId;+};++export default async function handler(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ try {+ // Verify admin API authentication, but allow non-langfuse cloud use-cases+ if (!AdminApiAuthService.handleAdminAuth(req, res, false)) {+ return;+ }++ // Handle different HTTP methods+ switch (req.method) {+ case "GET":+ return await handleGet(req, res);+ case "PUT":+ return await handlePut(req, res);+ case "DELETE":+ return await handleDelete(req, res);+ default:+ res.status(405).json({ error: "Method Not Allowed" });+ return;+ }+ } catch (e) {+ logger.error("Failed to process organization request", e);+ res.status(500).json({ error: "Internal server error" });+ }+}++async function handleGet(req: NextApiRequest, res: NextApiResponse) {+ const organizationId = validateQueryAndExtractId(req.query);+ if (!organizationId) {+ return res.status(400).json({ error: "Invalid organization ID" });+ }++ const organization = await prisma.organization.findUnique({+ where: { id: organizationId },+ select: {+ id: true,+ name: true,+ createdAt: true,+ },+ });++ if (!organization) {+ return res.status(404).json({ error: "Organization not found" });+ }++ return res.status(200).json(organization);+}++async function handlePut(req: NextApiRequest, res: NextApiResponse) {+ const organizationId = validateQueryAndExtractId(req.query);+ if (!organizationId) {+ return res.status(400).json({ error: "Invalid organization ID" });+ }++ const validationResult = organizationNameSchema.safeParse(req.body);++ if (!validationResult.success) {+ return res.status(400).json({+ error: "Invalid request body",+ details: validationResult.error.format(),+ });+ }++ const { name } = validationResult.data;++ // Check if organization exists+ const existingOrg = await prisma.organization.findUnique({+ where: { id: organizationId },+ });++ if (!existingOrg) {+ return res.status(404).json({ error: "Organization not found" });+ }++ // Update the organization+ const updatedOrganization = await prisma.organization.update({+ where: { id: organizationId },+ data: { name },+ });++ // Log the update+ await auditLog({+ resourceType: "organization",+ resourceId: organizationId,+ action: "update",+ orgId: organizationId,+ orgRole: "ADMIN",+ before: existingOrg,+ after: updatedOrganization,+ apiKeyId: "ADMIN_KEY",+ });++ logger.info(`Updated organization ${organizationId} via admin API`);++ return res.status(200).json({+ id: updatedOrganization.id,+ name: updatedOrganization.name,+ createdAt: updatedOrganization.createdAt,+ });+}++async function handleDelete(req: NextApiRequest, res: NextApiResponse) {+ const organizationId = validateQueryAndExtractId(req.query);+ if (!organizationId) {+ return res.status(400).json({ error: "Invalid organization ID" });+ }++ // Check if organization exists+ const existingOrg = await prisma.organization.findUnique({+ where: { id: organizationId },+ });++ if (!existingOrg) {+ return res.status(404).json({ error: "Organization not found" });+ }++ // Check if organization has any projects+ const projectCount = await prisma.project.count({+ where: { orgId: organizationId },+ });++ if (projectCount > 0) {+ return res.status(400).json({+ error: "Cannot delete organization with existing projects",+ message:+ "Please delete or transfer all projects before deleting the organization.",+ });+ }++ // Delete the organization+ const deletedOrganization = await prisma.organization.delete({+ where: { id: organizationId },+ });++ // Log the deletion+ await auditLog({+ resourceType: "organization",+ resourceId: organizationId,+ action: "delete",+ orgId: organizationId,+ orgRole: "ADMIN",+ before: deletedOrganization,+ apiKeyId: "ADMIN_KEY",+ });++ logger.info(`Deleted organization ${organizationId} via admin API`);++ return res.status(200).json({ success: true });+}diff --git a/web/src/pages/api/admin/organizations/apiKey.ts b/web/src/pages/api/admin/organizations/apiKey.tsnew file mode 100644index 0000000000..e69de29bb2diff --git a/web/src/pages/api/admin/organizations/index.ts b/web/src/pages/api/admin/organizations/index.tsindex 6b457e7718..dd853aac59 100644--- a/web/src/pages/api/admin/organizations/index.ts+++ b/web/src/pages/api/admin/organizations/index.ts@@ -11,7 +11,7 @@ export default async function handler() {try {// Allow only POST requests- if (req.method !== "POST") {+ if (req.method !== "POST" && req.method !== "GET") {res.status(405).json({ error: "Method Not Allowed" });return;}@@ -21,6 +21,18 @@ export default async function handler(return;}+ // For GET requests, return all organizations+ if (req.method === "GET") {+ const organizations = await prisma.organization.findMany({+ select: {+ id: true,+ name: true,+ createdAt: true,+ },+ });+ return res.status(200).json({ organizations });+ }+// For POST requests, create a new organizationif (req.method === "POST") {// Validate the request body using the organizationNameSchema