From d0af8bc57cb91c5e72dd463eb5d64268e89206d0 Mon Sep 17 00:00:00 2001 From: Agusti Fernandez Pardo Date: Thu, 7 Apr 2022 21:57:41 +0200 Subject: [PATCH] adds hashedKey to api key model, add frontend api keys in security page --- .../components/apiKeys/ApiKeyDialogForm.tsx | 18 +++++--------- apps/web/server/routers/viewer/apiKeys.tsx | 22 +++++++++++------ packages/ee/lib/api/apiKeys.ts | 24 +++++++++++++++++++ 3 files changed, 45 insertions(+), 19 deletions(-) create mode 100644 packages/ee/lib/api/apiKeys.ts diff --git a/apps/web/ee/components/apiKeys/ApiKeyDialogForm.tsx b/apps/web/ee/components/apiKeys/ApiKeyDialogForm.tsx index 28232895b4..6d2984d422 100644 --- a/apps/web/ee/components/apiKeys/ApiKeyDialogForm.tsx +++ b/apps/web/ee/components/apiKeys/ApiKeyDialogForm.tsx @@ -48,15 +48,9 @@ export default function ApiKeyDialogForm(props: { defaultValues?: TApiKeys; hand data-testid="ApiKeyDialogForm" form={form} handleSubmit={async (event) => { - if (event.id) { - await utils.client.mutation("viewer.apiKeys.edit", event); - await utils.invalidateQueries(["viewer.apiKeys.list"]); - showToast(t("apiKeys_updated_successfully"), "success"); - } else { - await utils.client.mutation("viewer.apiKeys.create", e); - await utils.invalidateQueries(["viewer.apiKeys.list"]); - showToast(t("apiKeys_created_successfully"), "success"); - } + await utils.client.mutation("viewer.apiKeys.create", event); + await utils.invalidateQueries(["viewer.apiKeys.list"]); + showToast(t("apiKeys_created_successfully"), "success"); props.handleClose(); }} className="space-y-4"> @@ -73,7 +67,7 @@ export default function ApiKeyDialogForm(props: { defaultValues?: TApiKeys; hand
Expire date - + {/* )} - /> + /> */}
{ + console.log(e); + }); + return apiKey; }, }) .mutation("edit", { diff --git a/packages/ee/lib/api/apiKeys.ts b/packages/ee/lib/api/apiKeys.ts new file mode 100644 index 0000000000..e68704f55d --- /dev/null +++ b/packages/ee/lib/api/apiKeys.ts @@ -0,0 +1,24 @@ +import { randomBytes } from "crypto"; + +import prisma from "@calcom/prisma"; + +export function generateUniqueAPIKey() { + const apiKey = randomBytes(16).toString("hex"); + const hashedAPIKey = hashAPIKey(apiKey); + // const exists = await prisma.apiKey.findMany({ where: { hashedKey: hashedAPIKey } }); + // Ensure API key is unique done at db level + // if (!exists) { + // generateUniqueAPIKey(); + // } else { + return [hashedAPIKey, apiKey]; + // } +} + +// Hash the API key +export function hashAPIKey(apiKey: string): string { + const { createHash } = require("crypto"); + + const hashedAPIKey = createHash("sha256").update(apiKey).digest("hex"); + + return hashedAPIKey; +}