mirror of
https://github.com/fosrl/pangolin.git
synced 2026-08-12 15:30:53 +02:00
add page to retrieve user virtual api keys
This commit is contained in:
@@ -1650,6 +1650,18 @@ authenticated.get(
|
||||
virtualApiKey.listVirtualApiKeys
|
||||
);
|
||||
|
||||
authenticated.get(
|
||||
"/org/:orgId/my-virtual-api-keys",
|
||||
verifyOrgAccess,
|
||||
virtualApiKey.listMyVirtualApiKeys
|
||||
);
|
||||
|
||||
authenticated.get(
|
||||
"/org/:orgId/my-virtual-api-keys/:virtualApiKeyId",
|
||||
verifyOrgAccess,
|
||||
virtualApiKey.getMyVirtualApiKey
|
||||
);
|
||||
|
||||
authenticated.get(
|
||||
"/virtual-api-key/:virtualApiKeyId",
|
||||
verifyVirtualApiKeyAccess,
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
import { z } from "zod";
|
||||
import { db, virtualApiKeyResources, virtualApiKeys } from "@server/db";
|
||||
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";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { toPublicVirtualApiKey } from "@server/lib/virtualApiKey";
|
||||
import type { GetMyVirtualApiKeyResponse } from "@server/routers/virtualApiKey/types";
|
||||
|
||||
const paramsSchema = z.strictObject({
|
||||
orgId: z.string().nonempty(),
|
||||
virtualApiKeyId: z.string().nonempty()
|
||||
});
|
||||
|
||||
registry.registerPath({
|
||||
method: "get",
|
||||
path: "/org/{orgId}/my-virtual-api-keys/{virtualApiKeyId}",
|
||||
description:
|
||||
"Get a virtual API key owned by the signed-in user, including the decrypted secret.",
|
||||
tags: [OpenAPITags.VirtualApiKey],
|
||||
request: {
|
||||
params: paramsSchema
|
||||
},
|
||||
responses: {
|
||||
200: {
|
||||
description: "Successful response"
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
export async function getMyVirtualApiKey(
|
||||
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 { orgId, virtualApiKeyId } = parsedParams.data;
|
||||
const userId = req.user?.userId;
|
||||
|
||||
if (!userId) {
|
||||
return next(
|
||||
createHttpError(HttpCode.UNAUTHORIZED, "User not authenticated")
|
||||
);
|
||||
}
|
||||
|
||||
if (orgId !== req.userOrgId) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.FORBIDDEN,
|
||||
"User does not have access to this organization"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const [key] = await db
|
||||
.select()
|
||||
.from(virtualApiKeys)
|
||||
.where(
|
||||
and(
|
||||
eq(virtualApiKeys.virtualApiKeyId, virtualApiKeyId),
|
||||
eq(virtualApiKeys.orgId, orgId),
|
||||
eq(virtualApiKeys.userId, userId)
|
||||
)
|
||||
)
|
||||
.limit(1);
|
||||
|
||||
if (!key) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.NOT_FOUND,
|
||||
`Virtual API key with ID ${virtualApiKeyId} not found`
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const resourceRows = await db
|
||||
.select({ resourceId: virtualApiKeyResources.resourceId })
|
||||
.from(virtualApiKeyResources)
|
||||
.where(eq(virtualApiKeyResources.virtualApiKeyId, virtualApiKeyId));
|
||||
|
||||
return response<GetMyVirtualApiKeyResponse>(res, {
|
||||
data: {
|
||||
virtualApiKey: {
|
||||
...toPublicVirtualApiKey(key, { includeSecret: true }),
|
||||
resourceIds: resourceRows.map((row) => row.resourceId)
|
||||
}
|
||||
},
|
||||
success: true,
|
||||
error: false,
|
||||
message: "Virtual API key retrieved successfully",
|
||||
status: HttpCode.OK
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error(error);
|
||||
return next(
|
||||
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
export * from "./createVirtualApiKey";
|
||||
export * from "./listVirtualApiKeys";
|
||||
export * from "./listMyVirtualApiKeys";
|
||||
export * from "./getVirtualApiKey";
|
||||
export * from "./getMyVirtualApiKey";
|
||||
export * from "./updateVirtualApiKey";
|
||||
export * from "./deleteVirtualApiKey";
|
||||
export * from "./types";
|
||||
|
||||
@@ -0,0 +1,219 @@
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
db,
|
||||
resources,
|
||||
virtualApiKeyResources,
|
||||
virtualApiKeys,
|
||||
type VirtualApiKey
|
||||
} from "@server/db";
|
||||
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";
|
||||
import { and, asc, eq, exists, inArray, or } from "drizzle-orm";
|
||||
import {
|
||||
getOrCreateUserVirtualApiKey,
|
||||
toPublicVirtualApiKey
|
||||
} from "@server/lib/virtualApiKey";
|
||||
import type { ListMyVirtualApiKeysResponse } from "@server/routers/virtualApiKey/types";
|
||||
|
||||
const paramsSchema = z.strictObject({
|
||||
orgId: z.string().nonempty()
|
||||
});
|
||||
|
||||
const querySchema = z.object({
|
||||
resourceGuid: z.string().nonempty().optional()
|
||||
});
|
||||
|
||||
registry.registerPath({
|
||||
method: "get",
|
||||
path: "/org/{orgId}/my-virtual-api-keys",
|
||||
description:
|
||||
"List the signed-in user's identity virtual API key and manual keys attributed to them.",
|
||||
tags: [OpenAPITags.VirtualApiKey],
|
||||
request: {
|
||||
params: paramsSchema,
|
||||
query: querySchema
|
||||
},
|
||||
responses: {
|
||||
200: {
|
||||
description: "Successful response"
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
async function resourceIdsForKeys(
|
||||
keyIds: string[]
|
||||
): Promise<Map<string, number[]>> {
|
||||
const resourceIdsByKey = new Map<string, number[]>();
|
||||
if (keyIds.length === 0) {
|
||||
return resourceIdsByKey;
|
||||
}
|
||||
|
||||
const resourceRows = await db
|
||||
.select()
|
||||
.from(virtualApiKeyResources)
|
||||
.where(inArray(virtualApiKeyResources.virtualApiKeyId, keyIds));
|
||||
|
||||
for (const row of resourceRows) {
|
||||
const existing = resourceIdsByKey.get(row.virtualApiKeyId) ?? [];
|
||||
existing.push(row.resourceId);
|
||||
resourceIdsByKey.set(row.virtualApiKeyId, existing);
|
||||
}
|
||||
|
||||
return resourceIdsByKey;
|
||||
}
|
||||
|
||||
function toKeyWithResources(
|
||||
row: VirtualApiKey,
|
||||
resourceIdsByKey: Map<string, number[]>
|
||||
) {
|
||||
return {
|
||||
...toPublicVirtualApiKey(row),
|
||||
resourceIds: resourceIdsByKey.get(row.virtualApiKeyId) ?? []
|
||||
};
|
||||
}
|
||||
|
||||
export async function listMyVirtualApiKeys(
|
||||
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 parsedQuery = querySchema.safeParse(req.query);
|
||||
if (!parsedQuery.success) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
fromError(parsedQuery.error).toString()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const { orgId } = parsedParams.data;
|
||||
const { resourceGuid } = parsedQuery.data;
|
||||
const userId = req.user?.userId;
|
||||
|
||||
if (!userId) {
|
||||
return next(
|
||||
createHttpError(HttpCode.UNAUTHORIZED, "User not authenticated")
|
||||
);
|
||||
}
|
||||
|
||||
if (orgId !== req.userOrgId) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.FORBIDDEN,
|
||||
"User does not have access to this organization"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
let resourceId: number | undefined;
|
||||
if (resourceGuid) {
|
||||
const [resource] = await db
|
||||
.select({
|
||||
resourceId: resources.resourceId
|
||||
})
|
||||
.from(resources)
|
||||
.where(
|
||||
and(
|
||||
eq(resources.resourceGuid, resourceGuid),
|
||||
eq(resources.orgId, orgId)
|
||||
)
|
||||
)
|
||||
.limit(1);
|
||||
|
||||
if (!resource) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.NOT_FOUND,
|
||||
`Resource with GUID ${resourceGuid} not found`
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
resourceId = resource.resourceId;
|
||||
}
|
||||
|
||||
const { key: userKeyRow } = await getOrCreateUserVirtualApiKey({
|
||||
orgId,
|
||||
userId,
|
||||
createdByUserId: userId
|
||||
});
|
||||
|
||||
const manualConditions = [
|
||||
eq(virtualApiKeys.orgId, orgId),
|
||||
eq(virtualApiKeys.userId, userId),
|
||||
eq(virtualApiKeys.kind, "manual")
|
||||
];
|
||||
|
||||
if (resourceId !== undefined) {
|
||||
manualConditions.push(
|
||||
or(
|
||||
eq(virtualApiKeys.allResources, true),
|
||||
exists(
|
||||
db
|
||||
.select()
|
||||
.from(virtualApiKeyResources)
|
||||
.where(
|
||||
and(
|
||||
eq(
|
||||
virtualApiKeyResources.virtualApiKeyId,
|
||||
virtualApiKeys.virtualApiKeyId
|
||||
),
|
||||
eq(
|
||||
virtualApiKeyResources.resourceId,
|
||||
resourceId
|
||||
)
|
||||
)
|
||||
)
|
||||
)
|
||||
)!
|
||||
);
|
||||
}
|
||||
|
||||
const manualRows = await db
|
||||
.select()
|
||||
.from(virtualApiKeys)
|
||||
.where(and(...manualConditions))
|
||||
.orderBy(asc(virtualApiKeys.name), asc(virtualApiKeys.createdAt));
|
||||
|
||||
const allKeyIds = [
|
||||
userKeyRow.virtualApiKeyId,
|
||||
...manualRows.map((row) => row.virtualApiKeyId)
|
||||
];
|
||||
const resourceIdsByKey = await resourceIdsForKeys(allKeyIds);
|
||||
|
||||
return response<ListMyVirtualApiKeysResponse>(res, {
|
||||
data: {
|
||||
userKey: toKeyWithResources(userKeyRow, resourceIdsByKey),
|
||||
manualKeys: manualRows.map((row) =>
|
||||
toKeyWithResources(row, resourceIdsByKey)
|
||||
)
|
||||
},
|
||||
success: true,
|
||||
error: false,
|
||||
message: "Virtual API keys retrieved successfully",
|
||||
status: HttpCode.OK
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error(error);
|
||||
return next(
|
||||
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -3,14 +3,27 @@ import type { PaginatedResponse } from "@server/types/Pagination";
|
||||
|
||||
export type { PublicVirtualApiKey };
|
||||
|
||||
export type VirtualApiKeyWithResources = PublicVirtualApiKey & {
|
||||
resourceIds: number[];
|
||||
};
|
||||
|
||||
export type ListVirtualApiKeysResponse = PaginatedResponse<{
|
||||
virtualApiKeys: (PublicVirtualApiKey & { resourceIds: number[] })[];
|
||||
virtualApiKeys: VirtualApiKeyWithResources[];
|
||||
}>;
|
||||
|
||||
export type GetVirtualApiKeyResponse = {
|
||||
virtualApiKey: PublicVirtualApiKey & { resourceIds: number[] };
|
||||
virtualApiKey: VirtualApiKeyWithResources;
|
||||
};
|
||||
|
||||
export type CreateOrEditVirtualApiKeyResponse = {
|
||||
virtualApiKey: PublicVirtualApiKey & { resourceIds: number[] };
|
||||
virtualApiKey: VirtualApiKeyWithResources;
|
||||
};
|
||||
|
||||
export type ListMyVirtualApiKeysResponse = {
|
||||
userKey: VirtualApiKeyWithResources;
|
||||
manualKeys: VirtualApiKeyWithResources[];
|
||||
};
|
||||
|
||||
export type GetMyVirtualApiKeyResponse = {
|
||||
virtualApiKey: VirtualApiKeyWithResources;
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user