Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 68 additions & 0 deletions app/api/organizations/domains/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import { NextRequest, NextResponse } from "next/server";
import { getCorsHeaders } from "@/lib/networking/getCorsHeaders";
import { getOrgDomainsHandler } from "@/lib/organizations/getOrgDomainsHandler";
import { addOrgDomainHandler } from "@/lib/organizations/addOrgDomainHandler";
import { removeOrgDomainHandler } from "@/lib/organizations/removeOrgDomainHandler";

/**
* OPTIONS handler for CORS preflight requests.
*
* @returns A NextResponse with CORS headers.
*/
export async function OPTIONS() {
return new NextResponse(null, {
status: 200,
headers: getCorsHeaders(),
});
}

/**
* GET /api/organizations/domains
*
* Lists the email domains mapped to an organization. Accounts that sign up
* with an email at a mapped domain automatically join the organization.
* The caller must be a member of the organization or a Recoup admin.
*
* Query parameters:
* - organization_id (required): The organization's account ID (UUID)
*
* @param request - The request object
* @returns A NextResponse with the organization's domain mappings
*/
export async function GET(request: NextRequest) {
return getOrgDomainsHandler(request);
}

/**
* POST /api/organizations/domains
*
* Maps an email domain to an organization for automatic membership.
* Idempotent for the same organization; returns 409 when the domain is
* already mapped to a different organization.
*
* Body parameters:
* - organizationId (required): The organization's account ID (UUID)
* - domain (required): The email domain to map (e.g. "seekermusic.com")
*
* @param request - The request object containing the body
* @returns A NextResponse with the domain mapping
*/
export async function POST(request: NextRequest) {
return addOrgDomainHandler(request);
}

/**
* DELETE /api/organizations/domains
*
* Removes an email domain mapping from an organization. Idempotent.
*
* Query parameters:
* - organization_id (required): The organization's account ID (UUID)
* - domain (required): The email domain to unmap (e.g. "seekermusic.com")
*
* @param request - The request object
* @returns A NextResponse indicating success
*/
export async function DELETE(request: NextRequest) {
return removeOrgDomainHandler(request);
}
202 changes: 202 additions & 0 deletions lib/organizations/__tests__/addOrgDomainHandler.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,202 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { NextRequest, NextResponse } from "next/server";
import { addOrgDomainHandler } from "../addOrgDomainHandler";
import { validateAuthContext } from "@/lib/auth/validateAuthContext";
import { canManageOrganization } from "@/lib/organizations/canManageOrganization";
import { selectOrganizationDomain } from "@/lib/supabase/organization_domains/selectOrganizationDomain";
import { insertOrganizationDomain } from "@/lib/supabase/organization_domains/insertOrganizationDomain";

vi.mock("@/lib/auth/validateAuthContext", () => ({
validateAuthContext: vi.fn(),
}));

vi.mock("@/lib/organizations/canManageOrganization", () => ({
canManageOrganization: vi.fn(),
}));

vi.mock("@/lib/supabase/organization_domains/selectOrganizationDomain", () => ({
selectOrganizationDomain: vi.fn(),
}));

vi.mock("@/lib/supabase/organization_domains/insertOrganizationDomain", () => ({
insertOrganizationDomain: vi.fn(),
}));

const ORG_ID = "9f0b5f61-6f8d-4b64-92f5-0d1a5f0a1c2e";
const OTHER_ORG_ID = "1b2c3d4e-5f60-4a71-8b92-a3b4c5d6e7f8";

function makeRequest(body: unknown) {
return new NextRequest("http://x/api/organizations/domains", {
method: "POST",
body: JSON.stringify(body),
});
}

describe("addOrgDomainHandler", () => {
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(validateAuthContext).mockResolvedValue({
accountId: "acc-1",
orgId: null,
authToken: "token",
});
vi.mocked(canManageOrganization).mockResolvedValue(true);
vi.mocked(selectOrganizationDomain).mockResolvedValue(null);
});

describe("successful cases", () => {
it("inserts a new mapping with a normalized domain", async () => {
vi.mocked(insertOrganizationDomain).mockResolvedValue({
id: "dom-1",
domain: "seekermusic.com",
organization_id: ORG_ID,
created_at: "2026-01-01",
});

const response = await addOrgDomainHandler(
makeRequest({ organizationId: ORG_ID, domain: " @SeekerMusic.COM " }),
);
const body = await response.json();

expect(response.status).toBe(200);
expect(body).toEqual({
status: "success",
id: "dom-1",
domain: "seekermusic.com",
organization_id: ORG_ID,
});
expect(selectOrganizationDomain).toHaveBeenCalledWith("seekermusic.com");
expect(insertOrganizationDomain).toHaveBeenCalledWith({
domain: "seekermusic.com",
organizationId: ORG_ID,
});
});

it("is idempotent when the domain is already mapped to the same org", async () => {
vi.mocked(selectOrganizationDomain).mockResolvedValue({
id: "dom-1",
domain: "seekermusic.com",
organization_id: ORG_ID,
created_at: "2026-01-01",
});

const response = await addOrgDomainHandler(
makeRequest({ organizationId: ORG_ID, domain: "seekermusic.com" }),
);
const body = await response.json();

expect(response.status).toBe(200);
expect(body).toEqual({
status: "success",
id: "dom-1",
domain: "seekermusic.com",
organization_id: ORG_ID,
});
expect(insertOrganizationDomain).not.toHaveBeenCalled();
});
});

describe("error cases", () => {
it("returns the auth error response when unauthenticated", async () => {
const authError = NextResponse.json(
{ status: "error", message: "unauthorized" },
{ status: 401 },
);
vi.mocked(validateAuthContext).mockResolvedValue(authError);

const response = await addOrgDomainHandler(
makeRequest({ organizationId: ORG_ID, domain: "seekermusic.com" }),
);

expect(response.status).toBe(401);
expect(insertOrganizationDomain).not.toHaveBeenCalled();
});

it("returns 400 for an invalid body", async () => {
const response = await addOrgDomainHandler(
makeRequest({ organizationId: ORG_ID, domain: "not a domain" }),
);

expect(response.status).toBe(400);
const body = await response.json();
expect(body.status).toBe("error");
expect(typeof body.error).toBe("string");
});

it("returns 403 when the caller cannot manage the organization", async () => {
vi.mocked(canManageOrganization).mockResolvedValue(false);

const response = await addOrgDomainHandler(
makeRequest({ organizationId: ORG_ID, domain: "seekermusic.com" }),
);
const body = await response.json();

expect(response.status).toBe(403);
expect(body).toEqual({
status: "error",
error: "Access denied to specified organization_id",
});
expect(insertOrganizationDomain).not.toHaveBeenCalled();
});

it("returns 409 when the domain is mapped to a different org", async () => {
vi.mocked(selectOrganizationDomain).mockResolvedValue({
id: "dom-1",
domain: "seekermusic.com",
organization_id: OTHER_ORG_ID,
created_at: "2026-01-01",
});

const response = await addOrgDomainHandler(
makeRequest({ organizationId: ORG_ID, domain: "seekermusic.com" }),
);
const body = await response.json();

expect(response.status).toBe(409);
expect(body.status).toBe("error");
expect(body.error).toContain("already mapped");
expect(insertOrganizationDomain).not.toHaveBeenCalled();
});

it("returns 500 when the insert fails", async () => {
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
vi.mocked(insertOrganizationDomain).mockResolvedValue(null);

const response = await addOrgDomainHandler(
makeRequest({ organizationId: ORG_ID, domain: "seekermusic.com" }),
);
const body = await response.json();

expect(response.status).toBe(500);
expect(body.status).toBe("error");
expect(typeof body.error).toBe("string");
});

it("returns 500 and does not insert when the existing-mapping lookup fails", async () => {
vi.mocked(selectOrganizationDomain).mockRejectedValue(
new Error("Failed to fetch organization_domain: boom"),
);

const response = await addOrgDomainHandler(
makeRequest({ organizationId: ORG_ID, domain: "seekermusic.com" }),
);
const body = await response.json();

expect(response.status).toBe(500);
expect(body).toEqual({ status: "error", error: "Internal server error" });
expect(insertOrganizationDomain).not.toHaveBeenCalled();
});

it("returns a generic 500 without leaking exception details when a dependency throws", async () => {
vi.mocked(insertOrganizationDomain).mockRejectedValue(new Error("SECRET_DB_DETAIL"));

const response = await addOrgDomainHandler(
makeRequest({ organizationId: ORG_ID, domain: "seekermusic.com" }),
);
const body = await response.json();

expect(response.status).toBe(500);
expect(body).toEqual({ status: "error", error: "Internal server error" });
expect(JSON.stringify(body)).not.toContain("SECRET_DB_DETAIL");
});
});
});
22 changes: 11 additions & 11 deletions lib/organizations/__tests__/addOrgMemberHandler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { NextRequest, NextResponse } from "next/server";
import { addOrgMemberHandler } from "../addOrgMemberHandler";

import { validateAuthContext } from "@/lib/auth/validateAuthContext";
import { canManageOrgMembers } from "@/lib/organizations/canManageOrgMembers";
import { canManageOrganization } from "@/lib/organizations/canManageOrganization";
import { getOrCreateAccountByEmail } from "@/lib/accounts/getOrCreateAccountByEmail";
import { getAccountOrganizations } from "@/lib/supabase/account_organization_ids/getAccountOrganizations";
import { addAccountToOrganization } from "@/lib/supabase/account_organization_ids/addAccountToOrganization";
Expand All @@ -12,8 +12,8 @@ vi.mock("@/lib/auth/validateAuthContext", () => ({
validateAuthContext: vi.fn(),
}));

vi.mock("@/lib/organizations/canManageOrgMembers", () => ({
canManageOrgMembers: vi.fn(),
vi.mock("@/lib/organizations/canManageOrganization", () => ({
canManageOrganization: vi.fn(),
}));

vi.mock("@/lib/accounts/getOrCreateAccountByEmail", () => ({
Expand Down Expand Up @@ -46,7 +46,7 @@ describe("addOrgMemberHandler", () => {
orgId: null,
authToken: "token",
});
vi.mocked(canManageOrgMembers).mockResolvedValue(true);
vi.mocked(canManageOrganization).mockResolvedValue(true);
vi.mocked(getAccountOrganizations).mockResolvedValue([]);
vi.mocked(addAccountToOrganization).mockResolvedValue("membership-1");
});
Expand Down Expand Up @@ -124,7 +124,7 @@ describe("addOrgMemberHandler", () => {
);

expect(response.status).toBe(401);
expect(canManageOrgMembers).not.toHaveBeenCalled();
expect(canManageOrganization).not.toHaveBeenCalled();
});

it("returns 400 when the body is invalid", async () => {
Expand All @@ -133,7 +133,7 @@ describe("addOrgMemberHandler", () => {
expect(response.status).toBe(400);
const body = await response.json();
expect(body.status).toBe("error");
expect(typeof body.message).toBe("string");
expect(typeof body.error).toBe("string");
});

it("returns 400 when the body is not valid JSON", async () => {
Expand All @@ -148,7 +148,7 @@ describe("addOrgMemberHandler", () => {
});

it("returns 403 when the caller cannot manage the organization", async () => {
vi.mocked(canManageOrgMembers).mockResolvedValue(false);
vi.mocked(canManageOrganization).mockResolvedValue(false);

const response = await addOrgMemberHandler(
buildRequest({ organizationId: ORG_ID, accountId: MEMBER_ID }),
Expand All @@ -157,8 +157,8 @@ describe("addOrgMemberHandler", () => {
expect(response.status).toBe(403);
const body = await response.json();
expect(body.status).toBe("error");
expect(typeof body.message).toBe("string");
expect(canManageOrgMembers).toHaveBeenCalledWith({
expect(typeof body.error).toBe("string");
expect(canManageOrganization).toHaveBeenCalledWith({
accountId: "caller-1",
organizationId: ORG_ID,
});
Expand Down Expand Up @@ -186,7 +186,7 @@ describe("addOrgMemberHandler", () => {
expect(response.status).toBe(500);
const body = await response.json();
expect(body.status).toBe("error");
expect(body.message).toBe("Failed to add member to organization");
expect(body.error).toBe("Failed to add member to organization");
});

it("returns a generic 500 without leaking exception details when a dependency throws", async () => {
Expand All @@ -198,7 +198,7 @@ describe("addOrgMemberHandler", () => {

expect(response.status).toBe(500);
const body = await response.json();
expect(body).toEqual({ status: "error", message: "Internal server error" });
expect(body).toEqual({ status: "error", error: "Internal server error" });
expect(JSON.stringify(body)).not.toContain("SECRET_DB_DETAIL");
});
});
Expand Down
Loading
Loading