Skip to content

Commit

Permalink
fix: changed api key id to uuid
Browse files Browse the repository at this point in the history
  • Loading branch information
arybitskiy committed Nov 25, 2024
1 parent 210f14f commit eea3060
Show file tree
Hide file tree
Showing 14 changed files with 105 additions and 69 deletions.
5 changes: 3 additions & 2 deletions apps/backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,17 +55,18 @@
"fuse.js": "catalog:",
"ioredis": "catalog:",
"langchain": "catalog:",
"lodash-es": "catalog:",
"openai": "catalog:",
"openai-edge": "catalog:",
"parse-github-url": "catalog:",
"pg": "catalog:",
"replicate": "catalog:",
"semver": "7.6.0",
"tar": "^6.2.0",
"uuid": "^11.0.3",
"valibot": "catalog:",
"ws": "^8.18.0",
"zod": "catalog:",
"lodash-es": "catalog:"
"zod": "catalog:"
},
"type": "module",
"peerDependencies": {
Expand Down
10 changes: 8 additions & 2 deletions apps/backend/src/handlers/createAPIKeyHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
import type { UserDataPopulatedRequest } from "@codemod-com/auth";
import { prisma } from "@codemod-com/database";
import type { RouteHandler } from "fastify";
import { v4 as uuidv4 } from "uuid";
import { parse } from "valibot";
import { createApiKey } from "../services/UnkeyService.js";

Expand All @@ -13,17 +14,22 @@ export const createAPIKeyHandler: RouteHandler<{
}> = async (request: UserDataPopulatedRequest) => {
const user = request.user!;

const uuid = uuidv4();

const apiKey = await createApiKey({
externalId: user.id,
apiKeyData: parse(createAPIKeyRequestSchema, request.body),
uuid,
});

await prisma.apiKey.create({
data: {
...apiKey,
externalId: user.id,
uuid,
keyId: apiKey.keyId,
},
});

return { key: apiKey.key };
const reply: CreateAPIKeyResponse = { key: apiKey.key, uuid };
return reply;
};
9 changes: 5 additions & 4 deletions apps/backend/src/handlers/deleteAPIKeysHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@ export const deleteAPIKeysHandler: RouteHandler<{
}> = async (request: UserDataPopulatedRequest) => {
const user = request.user!;

const { includes } = parse(deleteAPIKeysRequestSchema, request.params);
const { uuid } = parse(deleteAPIKeysRequestSchema, request.params);

const keysToDelete = await prisma.apiKey.findMany({
where: { externalId: user.id, key: { contains: includes } },
where: { externalId: user.id, uuid },
});

const keysInfo = await listApiKeys({ externalId: user.id });
Expand All @@ -30,10 +30,11 @@ export const deleteAPIKeysHandler: RouteHandler<{
},
});

return {
const reply: DeleteAPIKeysResponse = {
keys: keysToDelete
.map(({ key }) => keysInfo.keys.find((k) => key.startsWith(k.start)))
.map(({ uuid }) => keysInfo.keys.find((k) => k.meta?.uuid === uuid))
.filter((key) => !!key)
.map(({ start, name }) => ({ start, name })),
};
return reply;
};
10 changes: 7 additions & 3 deletions apps/backend/src/handlers/listAPIKeysHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,18 @@ export const listAPIKeysHandler: RouteHandler<{
}> = async (request: UserDataPopulatedRequest) => {
const user = request.user!;

const apiKeys = await listApiKeys({ externalId: user.id });
const apiKeys = await listApiKeys({ externalId: user.id }).then(
({ keys }) => keys,
);

return {
keys: apiKeys.keys.map(({ start, name, createdAt, expires }) => ({
const reply: ListAPIKeysResponse = {
keys: apiKeys.map(({ start, name, createdAt, expires, meta }) => ({
start,
name,
createdAt,
expiresAt: expires,
uuid: meta?.uuid as string | undefined,
})),
};
return reply;
};
2 changes: 1 addition & 1 deletion apps/backend/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ const routes: FastifyPluginCallback = (instance, _opts, done) => {
instance.delete<{
Reply: DeleteAPIKeysResponse;
}>(
"/api-keys/:includes",
"/api-keys/:uuid",
{ preHandler: instance.getUserData },
deleteAPIKeysHandler,
);
Expand Down
6 changes: 5 additions & 1 deletion apps/backend/src/services/UnkeyService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ const getUnkey = memoize(() => new Unkey({ rootKey: UNKEY_ROOT_KEY }));
export const createApiKey = async ({
apiKeyData,
externalId,
}: { apiKeyData: CreateAPIKeyRequest; externalId: string }) => {
uuid,
}: { apiKeyData: CreateAPIKeyRequest; externalId: string; uuid: string }) => {
const response = await getUnkey().keys.create({
apiId: UNKEY_API_ID,
prefix: "codemod.com",
Expand All @@ -19,6 +20,9 @@ export const createApiKey = async ({
expires: apiKeyData.expiresAt
? Date.parse(apiKeyData.expiresAt)
: undefined,
meta: {
uuid,
},
});

if (response.error) {
Expand Down
2 changes: 1 addition & 1 deletion apps/cli/src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ export const deleteAPIKeys = async (
const url = new URL(`${process.env.BACKEND_URL}/api-keys`);

const res = await Axios.delete<DeleteAPIKeysResponse>(
`${url.toString()}/${data.includes}`,
`${url.toString()}/${data.uuid}`,
{
headers: { Authorization: `Bearer ${accessToken}` },
timeout: 10000,
Expand Down
5 changes: 3 additions & 2 deletions apps/cli/src/commands/api-keys.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@ export const handleCreateAPIKeyCommand = async (options: {
"info",
`
${options.data.name ?? ""}
API key created successfully: ${apiKey.key}
API key with id ${apiKey.uuid} created successfully:
${apiKey.key}
Please store this key in a safe place, as it will not be shown again.`,
);
};
Expand All @@ -49,7 +50,7 @@ export const handleListAPIKeysCommand = async (options: {
"info",
`
API keys:
${keys.map(({ name, start, createdAt, expiresAt }) => ` - ${[name, `${start}...`, `created at ${new Date(createdAt).toISOString()}`, expiresAt ? `expires at ${new Date(expiresAt).toISOString()}` : undefined].filter((info) => !!info).join("\n ")}`).join("\n")}
${keys.map(({ name, start, createdAt, expiresAt, uuid }) => ` - ${[name, `${start}...`, `created at ${new Date(createdAt).toISOString()}`, expiresAt ? `expires at ${new Date(expiresAt).toISOString()}` : undefined, uuid ? `id: ${uuid}` : undefined].filter((info) => !!info).join("\n ")}`).join("\n")}
`,
);
};
Expand Down
7 changes: 3 additions & 4 deletions apps/cli/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -302,10 +302,9 @@ export const main = async () => {
"api-keys:delete",
"list API keys",
(y) =>
y.option("includes", {
y.option("id", {
type: "string",
description:
"Part of the key to delete. Every key that includes this string will be deleted.",
description: "Key id",
demandOption: true,
}),
async (args) => {
Expand All @@ -315,7 +314,7 @@ export const main = async () => {
return executeCliCommand(async () => {
await handleDeleteAPIKeysCommand({
printer,
data: { includes: args.includes },
data: { uuid: args.id },
});
});
},
Expand Down
5 changes: 3 additions & 2 deletions packages/api-types/src/api-keys.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export const createAPIKeyRequestSchema = object({
});

export const deleteAPIKeysRequestSchema = object({
includes: string(),
uuid: string(),
});

export type DeleteAPIKeysRequest = InferInput<
Expand All @@ -18,14 +18,15 @@ export type DeleteAPIKeysRequest = InferInput<

export type CreateAPIKeyRequest = InferInput<typeof createAPIKeyRequestSchema>;

export type CreateAPIKeyResponse = { key: string };
export type CreateAPIKeyResponse = { key: string; uuid: string };

export type ListAPIKeysResponse = {
keys: {
start: string;
name?: string;
createdAt: number;
expiresAt?: number;
uuid?: string;
}[];
};

Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
-- CreateTable
CREATE TABLE "ApiKey" (
"externalId" VARCHAR(32) NOT NULL,
"uuid" VARCHAR(36) NOT NULL,
"keyId" VARCHAR(32) NOT NULL,

CONSTRAINT "ApiKey_pkey" PRIMARY KEY ("uuid","keyId")
);
8 changes: 4 additions & 4 deletions packages/database/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,8 @@ model CodeDiff {
}

model ApiKey {
externalId String @db.VarChar(255)
key String @db.VarChar(255)
keyId String @db.VarChar(255)
@@id([key, keyId])
externalId String @db.VarChar(32)
uuid String @db.VarChar(36)
keyId String @db.VarChar(32)
@@id([uuid, keyId])
}
Loading

0 comments on commit eea3060

Please sign in to comment.