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
13 changes: 2 additions & 11 deletions lib/keys/createApiKeyHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,14 @@ import { NextRequest, NextResponse } from "next/server";
import { getCorsHeaders } from "@/lib/networking/getCorsHeaders";
import { validateCreateApiKeyBody } from "@/lib/keys/validateCreateApiKeyBody";
import { getAuthenticatedAccountId } from "@/lib/auth/getAuthenticatedAccountId";
import { createOrgApiKeysHandler } from "@/lib/keys/org/createOrgApiKeysHandler";
import { createKey } from "@/lib/keys/createKey";

/**
* Handler for creating a new API key.
* Handler for creating a new API key for the authenticated account.
* Requires authentication via Bearer token in Authorization header.
*
* Body parameters:
* - key_name (required): The name for the API key
* - organizationId (optional): If provided, creates a key for the organization
* after validating the authenticated account is a member.
*
* @param request - The request object containing the body with key_name.
* @returns A NextResponse with the generated API key.
Expand All @@ -32,14 +29,8 @@ export async function createApiKeyHandler(request: NextRequest): Promise<NextRes
return validatedBody;
}

const { key_name, organizationId } = validatedBody;
const { key_name } = validatedBody;

// If organizationId is provided, delegate to org-specific handler
if (organizationId) {
return createOrgApiKeysHandler(accountId, organizationId, key_name);
}

// Default: create key for the authenticated account
return createKey(accountId, key_name);
} catch (error) {
console.error("[ERROR] Error creating API key:", error);
Expand Down
94 changes: 15 additions & 79 deletions lib/keys/deleteApiKeyHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,11 @@ import { validateDeleteApiKeyBody } from "@/lib/keys/validateDeleteApiKeyBody";
import { deleteApiKey } from "@/lib/supabase/account_api_keys/deleteApiKey";
import { getAuthenticatedAccountId } from "@/lib/auth/getAuthenticatedAccountId";
import { getApiKeys } from "@/lib/supabase/account_api_keys/getApiKeys";
import { onlyOrgAccounts } from "@/lib/keys/org/onlyOrgAccounts";

/**
* Handler for deleting an API key.
* Requires authentication via Bearer token in Authorization header.
* Allows deleting API keys that belong to the authenticated account
* or to organizations the account is a member of.
* Only allows deleting keys that belong to the authenticated account.
*
* Body parameters:
* - id (required): The ID of the API key to delete
Expand All @@ -33,108 +31,46 @@ export async function deleteApiKeyHandler(request: NextRequest): Promise<NextRes
return validatedBody;
}

// Fetch the API key by ID
const { data: apiKeys, error: fetchError } = await getApiKeys({ id: validatedBody.id });
const { data: apiKeys, error: fetchError } = await getApiKeys({
id: validatedBody.id,
});

if (fetchError || !apiKeys || apiKeys.length === 0) {
return NextResponse.json(
{
status: "error",
message: "API key not found",
},
{
status: 404,
headers: getCorsHeaders(),
},
{ status: "error", message: "API key not found" },
{ status: 404, headers: getCorsHeaders() },
);
}

const key = apiKeys[0];

// Check if the key belongs to the authenticated account
if (key.account === accountId) {
// Direct ownership: proceed with deletion
const { error } = await deleteApiKey(validatedBody.id);

if (error) {
console.error("Error deleting API key:", error);
return NextResponse.json(
{
status: "error",
message: "Failed to delete API key",
},
{
status: 500,
headers: getCorsHeaders(),
},
);
}

return NextResponse.json(
{
status: "success",
message: "API key deleted successfully",
},
{
status: 200,
headers: getCorsHeaders(),
},
);
}

const membershipError = await onlyOrgAccounts(accountId, key.account);
if (membershipError) {
if (key.account !== accountId) {
return NextResponse.json(
{
status: "error",
message: "Access denied",
},
{
status: 404,
headers: getCorsHeaders(),
},
{ status: "error", message: "Access denied" },
{ status: 403, headers: getCorsHeaders() },
);
}

// Account is a member of the organization: proceed with deletion
const { error } = await deleteApiKey(validatedBody.id);

if (error) {
console.error("Error deleting API key:", error);
return NextResponse.json(
{
status: "error",
message: "Failed to delete API key",
},
{
status: 500,
headers: getCorsHeaders(),
},
{ status: "error", message: "Failed to delete API key" },
{ status: 500, headers: getCorsHeaders() },
);
}

return NextResponse.json(
{
status: "success",
message: "API key deleted successfully",
},
{
status: 200,
headers: getCorsHeaders(),
},
{ status: "success", message: "API key deleted successfully" },
{ status: 200, headers: getCorsHeaders() },
);
} catch (error) {
console.error("[ERROR] Error deleting API key:", error);
const message = error instanceof Error ? error.message : "Failed to delete API key";
return NextResponse.json(
{
status: "error",
message,
},
{
status: 500,
headers: getCorsHeaders(),
},
{ status: "error", message },
{ status: 500, headers: getCorsHeaders() },
);
}
}
16 changes: 1 addition & 15 deletions lib/keys/getApiKeysHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,36 +2,22 @@ import { NextRequest, NextResponse } from "next/server";
import { getCorsHeaders } from "@/lib/networking/getCorsHeaders";
import { getApiKeys } from "@/lib/supabase/account_api_keys/getApiKeys";
import { getAuthenticatedAccountId } from "@/lib/auth/getAuthenticatedAccountId";
import { getOrgApiKeysHandler } from "@/lib/keys/org/getOrgApiKeysHandler";

/**
* Handler for retrieving API keys for an account or organization.
* Handler for retrieving API keys for the authenticated account.
* Requires authentication via Bearer token in Authorization header.
*
* Optional query parameter:
* - organizationId: If provided, returns keys for the organization
* after validating the authenticated account is a member.
*
* @param request - The request object.
* @returns A NextResponse with the API keys.
*/
export async function getApiKeysHandler(request: NextRequest): Promise<NextResponse> {
try {
const { searchParams } = new URL(request.url);
const organizationId = searchParams.get("organizationId") ?? undefined;

const accountIdOrError = await getAuthenticatedAccountId(request);
if (accountIdOrError instanceof NextResponse) {
return accountIdOrError;
}
const accountId = accountIdOrError;

// If organizationId is provided, delegate to org-specific handler
if (organizationId) {
return getOrgApiKeysHandler(accountId, organizationId);
}

// Default: fetch keys for the authenticated account
const { data, error } = await getApiKeys({ accountId });

if (error) {
Expand Down
28 changes: 0 additions & 28 deletions lib/keys/org/createOrgApiKeysHandler.ts

This file was deleted.

50 changes: 0 additions & 50 deletions lib/keys/org/getOrgApiKeysHandler.ts

This file was deleted.

36 changes: 0 additions & 36 deletions lib/keys/org/onlyOrgAccounts.ts

This file was deleted.

1 change: 0 additions & 1 deletion lib/keys/validateCreateApiKeyBody.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { z } from "zod";

export const createApiKeyBodySchema = z.object({
key_name: z.string().min(1, "key_name parameter is required"),
organizationId: z.string().optional(),
});

export type CreateApiKeyBody = z.infer<typeof createApiKeyBodySchema>;
Expand Down
Loading