add api key code and oidc auto provision code

This commit is contained in:
miloschwartz 2025-04-28 21:14:09 -04:00
parent 4819f410e6
commit 599d0a52bf
No known key found for this signature in database
84 changed files with 7021 additions and 151 deletions

View file

@ -0,0 +1,133 @@
// This file is licensed under the Fossorial Commercial License.
// Unauthorized use, copying, modification, or distribution is strictly prohibited.
//
// Copyright (c) 2025 Fossorial LLC. All rights reserved.
import { NextFunction, Request, Response } from "express";
import db from "@server/db";
import HttpCode from "@server/types/HttpCode";
import { z } from "zod";
import { apiKeyOrg, apiKeys } from "@server/db/schemas";
import { fromError } from "zod-validation-error";
import createHttpError from "http-errors";
import response from "@server/lib/response";
import moment from "moment";
import {
generateId,
generateIdFromEntropySize
} from "@server/auth/sessions/app";
import logger from "@server/logger";
import { hashPassword } from "@server/auth/password";
import { OpenAPITags, registry } from "@server/openApi";
const paramsSchema = z.object({
orgId: z.string().nonempty()
});
const bodySchema = z.object({
name: z.string().min(1).max(255)
});
export type CreateOrgApiKeyBody = z.infer<typeof bodySchema>;
export type CreateOrgApiKeyResponse = {
apiKeyId: string;
name: string;
apiKey: string;
lastChars: string;
createdAt: string;
};
registry.registerPath({
method: "put",
path: "/org/{orgId}/api-key",
description: "Create a new API key scoped to the organization.",
tags: [OpenAPITags.Org, OpenAPITags.ApiKey],
request: {
params: paramsSchema,
body: {
content: {
"application/json": {
schema: bodySchema
}
}
}
},
responses: {}
});
export async function createOrgApiKey(
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
const parsedParams = paramsSchema.safeParse(req.params);
if (!parsedParams.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedParams.error).toString()
)
);
}
const parsedBody = bodySchema.safeParse(req.body);
if (!parsedBody.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedBody.error).toString()
)
);
}
const { orgId } = parsedParams.data;
const { name } = parsedBody.data;
const apiKeyId = generateId(15);
const apiKey = generateIdFromEntropySize(25);
const apiKeyHash = await hashPassword(apiKey);
const lastChars = apiKey.slice(-4);
const createdAt = moment().toISOString();
await db.transaction(async (trx) => {
await trx.insert(apiKeys).values({
name,
apiKeyId,
apiKeyHash,
createdAt,
lastChars
});
await trx.insert(apiKeyOrg).values({
apiKeyId,
orgId
});
});
try {
return response<CreateOrgApiKeyResponse>(res, {
data: {
apiKeyId,
apiKey,
name,
lastChars,
createdAt
},
success: true,
error: false,
message: "API key created",
status: HttpCode.CREATED
});
} catch (e) {
logger.error(e);
return next(
createHttpError(
HttpCode.INTERNAL_SERVER_ERROR,
"Failed to create API key"
)
);
}
}

View file

@ -0,0 +1,105 @@
// This file is licensed under the Fossorial Commercial License.
// Unauthorized use, copying, modification, or distribution is strictly prohibited.
//
// Copyright (c) 2025 Fossorial LLC. All rights reserved.
import { NextFunction, Request, Response } from "express";
import db from "@server/db";
import HttpCode from "@server/types/HttpCode";
import { z } from "zod";
import { apiKeyOrg, apiKeys, orgs } from "@server/db/schemas";
import { fromError } from "zod-validation-error";
import createHttpError from "http-errors";
import response from "@server/lib/response";
import moment from "moment";
import {
generateId,
generateIdFromEntropySize
} from "@server/auth/sessions/app";
import logger from "@server/logger";
import { hashPassword } from "@server/auth/password";
const bodySchema = z
.object({
name: z.string().min(1).max(255)
})
.strict();
export type CreateRootApiKeyBody = z.infer<typeof bodySchema>;
export type CreateRootApiKeyResponse = {
apiKeyId: string;
name: string;
apiKey: string;
lastChars: string;
createdAt: string;
};
export async function createRootApiKey(
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
const parsedBody = bodySchema.safeParse(req.body);
if (!parsedBody.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedBody.error).toString()
)
);
}
const { name } = parsedBody.data;
const apiKeyId = generateId(15);
const apiKey = generateIdFromEntropySize(25);
const apiKeyHash = await hashPassword(apiKey);
const lastChars = apiKey.slice(-4);
const createdAt = moment().toISOString();
await db.transaction(async (trx) => {
await trx.insert(apiKeys).values({
apiKeyId,
name,
apiKeyHash,
createdAt,
lastChars,
isRoot: true
});
const allOrgs = await trx.select().from(orgs);
for (const org of allOrgs) {
await trx.insert(apiKeyOrg).values({
apiKeyId,
orgId: org.orgId
});
}
});
try {
return response<CreateRootApiKeyResponse>(res, {
data: {
apiKeyId,
name,
apiKey,
lastChars,
createdAt
},
success: true,
error: false,
message: "API key created",
status: HttpCode.CREATED
});
} catch (e) {
logger.error(e);
return next(
createHttpError(
HttpCode.INTERNAL_SERVER_ERROR,
"Failed to create API key"
)
);
}
}

View file

@ -0,0 +1,81 @@
// This file is licensed under the Fossorial Commercial License.
// Unauthorized use, copying, modification, or distribution is strictly prohibited.
//
// Copyright (c) 2025 Fossorial LLC. All rights reserved.
import { Request, Response, NextFunction } from "express";
import { z } from "zod";
import { db } from "@server/db";
import { apiKeys } from "@server/db/schemas";
import { eq } from "drizzle-orm";
import response from "@server/lib/response";
import HttpCode from "@server/types/HttpCode";
import createHttpError from "http-errors";
import logger from "@server/logger";
import { fromError } from "zod-validation-error";
import { OpenAPITags, registry } from "@server/openApi";
const paramsSchema = z.object({
apiKeyId: z.string().nonempty()
});
registry.registerPath({
method: "delete",
path: "/org/{orgId}/api-key/{apiKeyId}",
description: "Delete an API key.",
tags: [OpenAPITags.Org, OpenAPITags.ApiKey],
request: {
params: paramsSchema
},
responses: {}
});
export async function deleteApiKey(
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
try {
const parsedParams = paramsSchema.safeParse(req.params);
if (!parsedParams.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedParams.error).toString()
)
);
}
const { apiKeyId } = parsedParams.data;
const [apiKey] = await db
.select()
.from(apiKeys)
.where(eq(apiKeys.apiKeyId, apiKeyId))
.limit(1);
if (!apiKey) {
return next(
createHttpError(
HttpCode.NOT_FOUND,
`API Key with ID ${apiKeyId} not found`
)
);
}
await db.delete(apiKeys).where(eq(apiKeys.apiKeyId, apiKeyId));
return response(res, {
data: null,
success: true,
error: false,
message: "API key deleted successfully",
status: HttpCode.OK
});
} catch (error) {
logger.error(error);
return next(
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
);
}
}

View file

@ -0,0 +1,104 @@
// This file is licensed under the Fossorial Commercial License.
// Unauthorized use, copying, modification, or distribution is strictly prohibited.
//
// Copyright (c) 2025 Fossorial LLC. All rights reserved.
import { Request, Response, NextFunction } from "express";
import { z } from "zod";
import { db } from "@server/db";
import { apiKeyOrg, apiKeys } from "@server/db/schemas";
import { and, eq } from "drizzle-orm";
import response from "@server/lib/response";
import HttpCode from "@server/types/HttpCode";
import createHttpError from "http-errors";
import logger from "@server/logger";
import { fromError } from "zod-validation-error";
const paramsSchema = z.object({
apiKeyId: z.string().nonempty(),
orgId: z.string().nonempty()
});
export async function deleteOrgApiKey(
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
try {
const parsedParams = paramsSchema.safeParse(req.params);
if (!parsedParams.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedParams.error).toString()
)
);
}
const { apiKeyId, orgId } = parsedParams.data;
const [apiKey] = await db
.select()
.from(apiKeys)
.where(eq(apiKeys.apiKeyId, apiKeyId))
.innerJoin(
apiKeyOrg,
and(
eq(apiKeys.apiKeyId, apiKeyOrg.apiKeyId),
eq(apiKeyOrg.orgId, orgId)
)
)
.limit(1);
if (!apiKey) {
return next(
createHttpError(
HttpCode.NOT_FOUND,
`API Key with ID ${apiKeyId} not found`
)
);
}
if (apiKey.apiKeys.isRoot) {
return next(
createHttpError(
HttpCode.FORBIDDEN,
"Cannot delete root API key"
)
);
}
await db.transaction(async (trx) => {
await trx
.delete(apiKeyOrg)
.where(
and(
eq(apiKeyOrg.apiKeyId, apiKeyId),
eq(apiKeyOrg.orgId, orgId)
)
);
const apiKeyOrgs = await db
.select()
.from(apiKeyOrg)
.where(eq(apiKeyOrg.apiKeyId, apiKeyId));
if (apiKeyOrgs.length === 0) {
await trx.delete(apiKeys).where(eq(apiKeys.apiKeyId, apiKeyId));
}
});
return response(res, {
data: null,
success: true,
error: false,
message: "API removed from organization",
status: HttpCode.OK
});
} catch (error) {
logger.error(error);
return next(
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
);
}
}

View file

@ -0,0 +1,81 @@
// This file is licensed under the Fossorial Commercial License.
// Unauthorized use, copying, modification, or distribution is strictly prohibited.
//
// Copyright (c) 2025 Fossorial LLC. All rights reserved.
import { Request, Response, NextFunction } from "express";
import { z } from "zod";
import { db } from "@server/db";
import { apiKeys } from "@server/db/schemas";
import { eq } from "drizzle-orm";
import response from "@server/lib/response";
import HttpCode from "@server/types/HttpCode";
import createHttpError from "http-errors";
import logger from "@server/logger";
import { fromError } from "zod-validation-error";
const paramsSchema = z.object({
apiKeyId: z.string().nonempty()
});
async function query(apiKeyId: string) {
return await db
.select({
apiKeyId: apiKeys.apiKeyId,
lastChars: apiKeys.lastChars,
createdAt: apiKeys.createdAt,
isRoot: apiKeys.isRoot,
name: apiKeys.name
})
.from(apiKeys)
.where(eq(apiKeys.apiKeyId, apiKeyId))
.limit(1);
}
export type GetApiKeyResponse = NonNullable<
Awaited<ReturnType<typeof query>>[0]
>;
export async function getApiKey(
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
try {
const parsedParams = paramsSchema.safeParse(req.params);
if (!parsedParams.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedParams.error).toString()
)
);
}
const { apiKeyId } = parsedParams.data;
const [apiKey] = await query(apiKeyId);
if (!apiKey) {
return next(
createHttpError(
HttpCode.NOT_FOUND,
`API Key with ID ${apiKeyId} not found`
)
);
}
return response<GetApiKeyResponse>(res, {
data: apiKey,
success: true,
error: false,
message: "API key deleted successfully",
status: HttpCode.OK
});
} catch (error) {
logger.error(error);
return next(
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
);
}
}

View file

@ -0,0 +1,16 @@
// This file is licensed under the Fossorial Commercial License.
// Unauthorized use, copying, modification, or distribution is strictly prohibited.
//
// Copyright (c) 2025 Fossorial LLC. All rights reserved.
export * from "./createRootApiKey";
export * from "./deleteApiKey";
export * from "./getApiKey";
export * from "./listApiKeyActions";
export * from "./listOrgApiKeys";
export * from "./listApiKeyActions";
export * from "./listRootApiKeys";
export * from "./setApiKeyActions";
export * from "./setApiKeyOrgs";
export * from "./createOrgApiKey";
export * from "./deleteOrgApiKey";

View file

@ -0,0 +1,118 @@
// This file is licensed under the Fossorial Commercial License.
// Unauthorized use, copying, modification, or distribution is strictly prohibited.
//
// Copyright (c) 2025 Fossorial LLC. All rights reserved.
import { db } from "@server/db";
import { actions, apiKeyActions, apiKeyOrg, apiKeys } from "@server/db/schemas";
import logger from "@server/logger";
import HttpCode from "@server/types/HttpCode";
import response from "@server/lib/response";
import { NextFunction, Request, Response } from "express";
import createHttpError from "http-errors";
import { z } from "zod";
import { fromError } from "zod-validation-error";
import { eq } from "drizzle-orm";
import { OpenAPITags, registry } from "@server/openApi";
const paramsSchema = z.object({
apiKeyId: z.string().nonempty()
});
const querySchema = z.object({
limit: z
.string()
.optional()
.default("1000")
.transform(Number)
.pipe(z.number().int().positive()),
offset: z
.string()
.optional()
.default("0")
.transform(Number)
.pipe(z.number().int().nonnegative())
});
function queryActions(apiKeyId: string) {
return db
.select({
actionId: actions.actionId
})
.from(apiKeyActions)
.where(eq(apiKeyActions.apiKeyId, apiKeyId))
.innerJoin(actions, eq(actions.actionId, apiKeyActions.actionId));
}
export type ListApiKeyActionsResponse = {
actions: Awaited<ReturnType<typeof queryActions>>;
pagination: { total: number; limit: number; offset: number };
};
registry.registerPath({
method: "get",
path: "/org/{orgId}/api-key/{apiKeyId}/actions",
description:
"List all actions set for an API key.",
tags: [OpenAPITags.Org, OpenAPITags.ApiKey],
request: {
params: paramsSchema,
query: querySchema
},
responses: {}
});
export async function listApiKeyActions(
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
try {
const parsedQuery = querySchema.safeParse(req.query);
if (!parsedQuery.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedQuery.error)
)
);
}
const parsedParams = paramsSchema.safeParse(req.params);
if (!parsedParams.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedParams.error)
)
);
}
const { limit, offset } = parsedQuery.data;
const { apiKeyId } = parsedParams.data;
const baseQuery = queryActions(apiKeyId);
const actionsList = await baseQuery.limit(limit).offset(offset);
return response<ListApiKeyActionsResponse>(res, {
data: {
actions: actionsList,
pagination: {
total: actionsList.length,
limit,
offset
}
},
success: true,
error: false,
message: "API keys retrieved successfully",
status: HttpCode.OK
});
} catch (error) {
logger.error(error);
return next(
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
);
}
}

View file

@ -0,0 +1,121 @@
// This file is licensed under the Fossorial Commercial License.
// Unauthorized use, copying, modification, or distribution is strictly prohibited.
//
// Copyright (c) 2025 Fossorial LLC. All rights reserved.
import { db } from "@server/db";
import { apiKeyOrg, apiKeys } from "@server/db/schemas";
import logger from "@server/logger";
import HttpCode from "@server/types/HttpCode";
import response from "@server/lib/response";
import { NextFunction, Request, Response } from "express";
import createHttpError from "http-errors";
import { z } from "zod";
import { fromError } from "zod-validation-error";
import { eq, and } from "drizzle-orm";
import { OpenAPITags, registry } from "@server/openApi";
const querySchema = z.object({
limit: z
.string()
.optional()
.default("1000")
.transform(Number)
.pipe(z.number().int().positive()),
offset: z
.string()
.optional()
.default("0")
.transform(Number)
.pipe(z.number().int().nonnegative())
});
const paramsSchema = z.object({
orgId: z.string()
});
function queryApiKeys(orgId: string) {
return db
.select({
apiKeyId: apiKeys.apiKeyId,
orgId: apiKeyOrg.orgId,
lastChars: apiKeys.lastChars,
createdAt: apiKeys.createdAt,
name: apiKeys.name
})
.from(apiKeyOrg)
.where(and(eq(apiKeyOrg.orgId, orgId), eq(apiKeys.isRoot, false)))
.innerJoin(apiKeys, eq(apiKeys.apiKeyId, apiKeyOrg.apiKeyId));
}
export type ListOrgApiKeysResponse = {
apiKeys: Awaited<ReturnType<typeof queryApiKeys>>;
pagination: { total: number; limit: number; offset: number };
};
registry.registerPath({
method: "get",
path: "/org/{orgId}/api-keys",
description: "List all API keys for an organization",
tags: [OpenAPITags.Org, OpenAPITags.ApiKey],
request: {
params: paramsSchema,
query: querySchema
},
responses: {}
});
export async function listOrgApiKeys(
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
try {
const parsedQuery = querySchema.safeParse(req.query);
if (!parsedQuery.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedQuery.error)
)
);
}
const parsedParams = paramsSchema.safeParse(req.params);
if (!parsedParams.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedParams.error)
)
);
}
const { limit, offset } = parsedQuery.data;
const { orgId } = parsedParams.data;
const baseQuery = queryApiKeys(orgId);
const apiKeysList = await baseQuery.limit(limit).offset(offset);
return response<ListOrgApiKeysResponse>(res, {
data: {
apiKeys: apiKeysList,
pagination: {
total: apiKeysList.length,
limit,
offset
}
},
success: true,
error: false,
message: "API keys retrieved successfully",
status: HttpCode.OK
});
} catch (error) {
logger.error(error);
return next(
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
);
}
}

View file

@ -0,0 +1,90 @@
// This file is licensed under the Fossorial Commercial License.
// Unauthorized use, copying, modification, or distribution is strictly prohibited.
//
// Copyright (c) 2025 Fossorial LLC. All rights reserved.
import { db } from "@server/db";
import { apiKeys } from "@server/db/schemas";
import logger from "@server/logger";
import HttpCode from "@server/types/HttpCode";
import response from "@server/lib/response";
import { NextFunction, Request, Response } from "express";
import createHttpError from "http-errors";
import { z } from "zod";
import { fromError } from "zod-validation-error";
import { eq } from "drizzle-orm";
const querySchema = z.object({
limit: z
.string()
.optional()
.default("1000")
.transform(Number)
.pipe(z.number().int().positive()),
offset: z
.string()
.optional()
.default("0")
.transform(Number)
.pipe(z.number().int().nonnegative())
});
function queryApiKeys() {
return db
.select({
apiKeyId: apiKeys.apiKeyId,
lastChars: apiKeys.lastChars,
createdAt: apiKeys.createdAt,
name: apiKeys.name
})
.from(apiKeys)
.where(eq(apiKeys.isRoot, true));
}
export type ListRootApiKeysResponse = {
apiKeys: Awaited<ReturnType<typeof queryApiKeys>>;
pagination: { total: number; limit: number; offset: number };
};
export async function listRootApiKeys(
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
try {
const parsedQuery = querySchema.safeParse(req.query);
if (!parsedQuery.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedQuery.error)
)
);
}
const { limit, offset } = parsedQuery.data;
const baseQuery = queryApiKeys();
const apiKeysList = await baseQuery.limit(limit).offset(offset);
return response<ListRootApiKeysResponse>(res, {
data: {
apiKeys: apiKeysList,
pagination: {
total: apiKeysList.length,
limit,
offset
}
},
success: true,
error: false,
message: "API keys retrieved successfully",
status: HttpCode.OK
});
} catch (error) {
logger.error(error);
return next(
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
);
}
}

View file

@ -0,0 +1,141 @@
// This file is licensed under the Fossorial Commercial License.
// Unauthorized use, copying, modification, or distribution is strictly prohibited.
//
// Copyright (c) 2025 Fossorial LLC. All rights reserved.
import { Request, Response, NextFunction } from "express";
import { z } from "zod";
import { db } from "@server/db";
import { actions, apiKeyActions } from "@server/db/schemas";
import response from "@server/lib/response";
import HttpCode from "@server/types/HttpCode";
import createHttpError from "http-errors";
import logger from "@server/logger";
import { fromError } from "zod-validation-error";
import { eq, and, inArray } from "drizzle-orm";
import { OpenAPITags, registry } from "@server/openApi";
const bodySchema = z
.object({
actionIds: z
.array(z.string().nonempty())
.transform((v) => Array.from(new Set(v)))
})
.strict();
const paramsSchema = z.object({
apiKeyId: z.string().nonempty()
});
registry.registerPath({
method: "post",
path: "/org/{orgId}/api-key/{apiKeyId}/actions",
description:
"Set actions for an API key. This will replace any existing actions.",
tags: [OpenAPITags.Org, OpenAPITags.ApiKey],
request: {
params: paramsSchema,
body: {
content: {
"application/json": {
schema: bodySchema
}
}
}
},
responses: {}
});
export async function setApiKeyActions(
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
try {
const parsedBody = bodySchema.safeParse(req.body);
if (!parsedBody.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedBody.error).toString()
)
);
}
const { actionIds: newActionIds } = parsedBody.data;
const parsedParams = paramsSchema.safeParse(req.params);
if (!parsedParams.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedParams.error).toString()
)
);
}
const { apiKeyId } = parsedParams.data;
const actionsExist = await db
.select()
.from(actions)
.where(inArray(actions.actionId, newActionIds));
if (actionsExist.length !== newActionIds.length) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"One or more actions do not exist"
)
);
}
await db.transaction(async (trx) => {
const existingActions = await trx
.select()
.from(apiKeyActions)
.where(eq(apiKeyActions.apiKeyId, apiKeyId));
const existingActionIds = existingActions.map((a) => a.actionId);
const actionIdsToAdd = newActionIds.filter(
(id) => !existingActionIds.includes(id)
);
const actionIdsToRemove = existingActionIds.filter(
(id) => !newActionIds.includes(id)
);
if (actionIdsToRemove.length > 0) {
await trx
.delete(apiKeyActions)
.where(
and(
eq(apiKeyActions.apiKeyId, apiKeyId),
inArray(apiKeyActions.actionId, actionIdsToRemove)
)
);
}
if (actionIdsToAdd.length > 0) {
const insertValues = actionIdsToAdd.map((actionId) => ({
apiKeyId,
actionId
}));
await trx.insert(apiKeyActions).values(insertValues);
}
});
return response(res, {
data: {},
success: true,
error: false,
message: "API key actions updated successfully",
status: HttpCode.OK
});
} catch (error) {
logger.error(error);
return next(
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
);
}
}

View file

@ -0,0 +1,122 @@
// This file is licensed under the Fossorial Commercial License.
// Unauthorized use, copying, modification, or distribution is strictly prohibited.
//
// Copyright (c) 2025 Fossorial LLC. All rights reserved.
import { Request, Response, NextFunction } from "express";
import { z } from "zod";
import { db } from "@server/db";
import { apiKeyOrg, orgs } from "@server/db/schemas";
import response from "@server/lib/response";
import HttpCode from "@server/types/HttpCode";
import createHttpError from "http-errors";
import logger from "@server/logger";
import { fromError } from "zod-validation-error";
import { eq, and, inArray } from "drizzle-orm";
const bodySchema = z
.object({
orgIds: z
.array(z.string().nonempty())
.transform((v) => Array.from(new Set(v)))
})
.strict();
const paramsSchema = z.object({
apiKeyId: z.string().nonempty()
});
export async function setApiKeyOrgs(
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
try {
const parsedBody = bodySchema.safeParse(req.body);
if (!parsedBody.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedBody.error).toString()
)
);
}
const { orgIds: newOrgIds } = parsedBody.data;
const parsedParams = paramsSchema.safeParse(req.params);
if (!parsedParams.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedParams.error).toString()
)
);
}
const { apiKeyId } = parsedParams.data;
// make sure all orgs exist
const allOrgs = await db
.select()
.from(orgs)
.where(inArray(orgs.orgId, newOrgIds));
if (allOrgs.length !== newOrgIds.length) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"One or more orgs do not exist"
)
);
}
await db.transaction(async (trx) => {
const existingOrgs = await trx
.select({ orgId: apiKeyOrg.orgId })
.from(apiKeyOrg)
.where(eq(apiKeyOrg.apiKeyId, apiKeyId));
const existingOrgIds = existingOrgs.map((a) => a.orgId);
const orgIdsToAdd = newOrgIds.filter(
(id) => !existingOrgIds.includes(id)
);
const orgIdsToRemove = existingOrgIds.filter(
(id) => !newOrgIds.includes(id)
);
if (orgIdsToRemove.length > 0) {
await trx
.delete(apiKeyOrg)
.where(
and(
eq(apiKeyOrg.apiKeyId, apiKeyId),
inArray(apiKeyOrg.orgId, orgIdsToRemove)
)
);
}
if (orgIdsToAdd.length > 0) {
const insertValues = orgIdsToAdd.map((orgId) => ({
apiKeyId,
orgId
}));
await trx.insert(apiKeyOrg).values(insertValues);
}
return response(res, {
data: {},
success: true,
error: false,
message: "API key orgs updated successfully",
status: HttpCode.OK
});
});
} catch (error) {
logger.error(error);
return next(
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
);
}
}