Skip to content

Same agent Smaller bill. The tools and infrastructure to get more work from your AI. Fewer tokens. Less compute. Lower cost.

feat: added page for managing api keys (#36)

Aman Agarwalb5a82a315961
diff --git a/src/client/package-lock.json b/src/client/package-lock.json
index ff48f0ff..0e7b36f4 100644
--- a/src/client/package-lock.json
+++ b/src/client/package-lock.json
@@ -14,6 +14,7 @@
"@prisma/client": "^5.8.1",
"@tremor/react": "^3.13.1",
"bcrypt-ts": "^5.0.1",
+ "copy-to-clipboard": "^3.3.3",
"date-fns": "^3.3.1",
"lodash": "^4.17.21",
"next": "14.0.4",
@@ -1462,6 +1463,14 @@
"node": ">= 0.6"
}
},
+ "node_modules/copy-to-clipboard": {
+ "version": "3.3.3",
+ "resolved": "https://registry.npmjs.org/copy-to-clipboard/-/copy-to-clipboard-3.3.3.tgz",
+ "integrity": "sha512-2KV8NhB5JqC3ky0r9PMCAZKbUHSwtEo4CwCs0KXgruG43gX5PMqDEBbVU4OUzw2MuAWUfsuFmWvEKG5QRfSnJA==",
+ "dependencies": {
+ "toggle-selection": "^1.0.6"
+ }
+ },
"node_modules/cross-spawn": {
"version": "7.0.3",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz",
@@ -4935,6 +4944,11 @@
"node": ">=8.0"
}
},
+ "node_modules/toggle-selection": {
+ "version": "1.0.6",
+ "resolved": "https://registry.npmjs.org/toggle-selection/-/toggle-selection-1.0.6.tgz",
+ "integrity": "sha512-BiZS+C1OS8g/q2RRbJmy59xpyghNBqrr6k5L/uKBGRsTfxmu3ffiRnd8mlGPUVayg8pvfi5urfnu8TU7DVOkLQ=="
+ },
"node_modules/ts-api-utils": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-1.0.3.tgz",
diff --git a/src/client/package.json b/src/client/package.json
index 6754d46a..0450a455 100644
--- a/src/client/package.json
+++ b/src/client/package.json
@@ -15,6 +15,7 @@
"@prisma/client": "^5.8.1",
"@tremor/react": "^3.13.1",
"bcrypt-ts": "^5.0.1",
+ "copy-to-clipboard": "^3.3.3",
"date-fns": "^3.3.1",
"lodash": "^4.17.21",
"next": "14.0.4",
diff --git a/src/client/prisma/schema.prisma b/src/client/prisma/schema.prisma
index f8c6e060..74cead32 100644
--- a/src/client/prisma/schema.prisma
+++ b/src/client/prisma/schema.prisma
@@ -11,6 +11,8 @@ model apikey {
id Int @id @default(autoincrement())
api_key String @unique @db.VarChar(255)
name String @db.VarChar(50)
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
@@index([api_key], map: "idx_api_key")
}
diff --git a/src/client/src/app/(playground)/api-keys/page.tsx b/src/client/src/app/(playground)/api-keys/page.tsx
new file mode 100644
index 00000000..731732f1
--- /dev/null
+++ b/src/client/src/app/(playground)/api-keys/page.tsx
@@ -0,0 +1,137 @@
+"use client";
+import AddAPIKeyModal from "@/components/(playground)/add-api-key-modal";
+import ConfirmationModal from "@/components/common/confirmation-modal";
+import { deleteData, getData } from "@/utils/api";
+import { DocumentDuplicateIcon, TrashIcon } from "@heroicons/react/24/outline";
+import { PlusIcon } from "@heroicons/react/24/solid";
+import copy from "copy-to-clipboard";
+import { useCallback, useEffect, useRef, useState } from "react";
+
+function ManageKeys() {
+ const [data, setData] = useState<Array<any>>([]);
+ const [selectedKey, setSelectedKey] = useState<any>();
+ const [creating, setCreating] = useState<boolean>(false);
+ const newCreatedKey = useRef<any>();
+ const fetchData = useCallback(async () => {
+ const res = await getData({
+ method: "GET",
+ url: "/api/api-key",
+ });
+
+ setData(res || []);
+ }, []);
+
+ useEffect(() => {
+ fetchData();
+ }, [fetchData]);
+
+ const handleYes = useCallback(async () => {
+ await deleteData({
+ url: `/api/api-key/${selectedKey?.id}`,
+ });
+
+ setSelectedKey(null);
+ fetchData();
+ }, [selectedKey, fetchData]);
+
+ const handleNo = () => setSelectedKey(null);
+
+ const handleYesCreation = async (name: string) => {
+ const res = await getData({
+ url: `/api/api-key`,
+ method: "POST",
+ body: JSON.stringify({ name }),
+ });
+
+ newCreatedKey.current = res;
+
+ setCreating(false);
+ fetchData();
+ };
+
+ const handleNoCreation = () => setCreating(false);
+
+ const copyAPIKey = () => copy(newCreatedKey.current?.api_key);
+
+ return (
+ <>
+ <table className="w-2/3 text-sm text-left rtl:text-right mt-4">
+ <thead className="text-xs text-gray-700 uppercase">
+ <tr className="border-b">
+ <th className="px-6 py-2 w-1/3">Name</th>
+ <th className="px-6 py-2 w-1/3">Key</th>
+ <th className="px-6 py-2 w-1/3">Actions</th>
+ </tr>
+ </thead>
+ <tbody>
+ {data.map((item) => (
+ <tr className="border-b" key={item.id}>
+ <td className="px-6 py-3 w-1/3 font-medium ">{item.name}</td>
+ <td className="px-6 py-3 w-1/3">
+ {item.api_key}
+ {newCreatedKey.current?.id === item.id && (
+ <DocumentDuplicateIcon
+ className="w-4 ml-1 inline cursor-pointer"
+ onClick={copyAPIKey}
+ />
+ )}
+ </td>
+ <td className="px-6 py-3 w-1/3">
+ <TrashIcon
+ className="w-4 cursor-pointer"
+ onClick={() => setSelectedKey(item)}
+ />
+ </td>
+ </tr>
+ ))}
+ <tr onClick={() => setCreating(true)}>
+ <td
+ className="w-full bg-gray-200 hover:bg-gray-300 cursor-pointer py-1"
+ colSpan={3}
+ >
+ <PlusIcon className="w-4 mx-auto" />
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ {selectedKey?.id && (
+ <ConfirmationModal handleNo={handleNo} handleYes={handleYes} />
+ )}
+ {creating && (
+ <AddAPIKeyModal
+ handleNo={handleNoCreation}
+ handleYes={handleYesCreation}
+ />
+ )}
+ </>
+ );
+}
+
+export default function APIKeys() {
+ return (
+ <div className="flex flex-col grow w-full h-full rounded overflow-hidden p-2 text-sm">
+ <p>
+ Welcome to the API Key Management page. Here, you can view, generate,
+ and manage API keys for seamless integration with our services. Please
+ note that we do not display your secret API keys again after you
+ generate them.
+ </p>
+ <ul className="list-disc list-inside mt-2">
+ <li>
+ <span className="font-medium">Keep Your Keys Secure:</span> Treat your
+ API keys like passwords. Do not share them publicly or expose them in
+ places where unauthorized individuals may access them.
+ </li>
+ <li>
+ <span className="font-medium">Rotate Keys Regularly:</span> For
+ enhanced security, consider rotating your keys periodically.
+ </li>
+ <li>
+ <span className="font-medium">Revoke Unused Keys:</span> If a key is
+ no longer needed or compromised, revoke it immediately.
+ </li>
+ </ul>
+ <ManageKeys />
+ </div>
+ );
+}
diff --git a/src/client/src/app/api/api-key/[id]/route.ts b/src/client/src/app/api/api-key/[id]/route.ts
new file mode 100644
index 00000000..66d1191f
--- /dev/null
+++ b/src/client/src/app/api/api-key/[id]/route.ts
@@ -0,0 +1,11 @@
+import { deleteAPIKey } from "@/lib/api-key";
+
+export async function DELETE(_: Request, context: any) {
+ const { id } = context.params;
+ const [err, res] = await deleteAPIKey(parseInt(id, 10));
+ if (err)
+ return Response.json(err, {
+ status: 400,
+ });
+ return Response.json(res);
+}
diff --git a/src/client/src/app/api/api-key/route.ts b/src/client/src/app/api/api-key/route.ts
new file mode 100644
index 00000000..92b97f24
--- /dev/null
+++ b/src/client/src/app/api/api-key/route.ts
@@ -0,0 +1,24 @@
+import { generateAPIKey, getAPIKeys } from "@/lib/api-key";
+
+export async function GET() {
+ const res: any = await getAPIKeys();
+ return Response.json(res);
+}
+
+export async function POST(request: Request) {
+ const formData = await request.json();
+ const name = formData.name;
+
+ if (!name)
+ return Response.json("Please provide a name for the key", {
+ status: 400,
+ });
+
+ const [err, res]: any = await generateAPIKey({ name });
+ if (err)
+ return Response.json(err, {
+ status: 400,
+ });
+
+ return Response.json(res);
+}
diff --git a/src/client/src/components/(playground)/add-api-key-modal.tsx b/src/client/src/components/(playground)/add-api-key-modal.tsx
new file mode 100644
index 00000000..b0b12f7f
--- /dev/null
+++ b/src/client/src/components/(playground)/add-api-key-modal.tsx
@@ -0,0 +1,64 @@
+import { XCircleIcon } from "@heroicons/react/24/outline";
+import { useRef } from "react";
+
+type AddAPIKeyModalProps = {
+ handleYes: (name: string) => void;
+ handleNo: () => void;
+};
+
+export default function AddAPIKeyModal(props: AddAPIKeyModalProps) {
+ const nameRef = useRef<HTMLInputElement>(null);
+
+ const handleYes = () => {
+ if (!nameRef.current?.value) return;
+ props.handleYes(nameRef.current.value);
+ };
+
+ return (
+ <div className="overflow-y-auto overflow-x-hidden fixed top-0 right-0 left-0 z-50 flex justify-center items-center w-full h-full bg-gray-900/[.6]">
+ <form>
+ <div className="relative p-4 w-full max-w-md h-full md:h-auto">
+ <div className="relative p-4 text-center bg-white rounded-lg shadow dark:bg-gray-800 sm:p-5">
+ <button
+ type="button"
+ className="text-gray-400 absolute top-2.5 right-2.5 bg-transparent hover:bg-gray-200 hover:text-gray-900 rounded-lg text-sm p-1.5 ml-auto inline-flex items-center dark:hover:bg-gray-600 dark:hover:text-white"
+ onClick={props.handleNo}
+ >
+ <XCircleIcon className="w-5" />
+ </button>
+ <p className="mb-4 text-gray-500 dark:text-gray-300">
+ Create an API Key
+ </p>
+ <div className="flex items-center my-3">
+ <label
+ htmlFor="name"
+ className="block text-sm font-medium leading-6 text-gray-900 mr-3"
+ >
+ Name :
+ </label>
+ <div className="flex rounded-md shadow-sm ring-1 ring-inset ring-gray-300 focus-within:ring-2 focus-within:ring-inset focus-within:ring-indigo-600 sm:max-w-md">
+ <input
+ type="text"
+ name="name"
+ className="block flex-1 border-0 bg-transparent py-1.5 pl-1 text-gray-900 placeholder:text-gray-400 focus:ring-0 sm:text-sm sm:leading-6 w-48"
+ placeholder="testing"
+ ref={nameRef}
+ required
+ />
+ </div>
+ </div>
+ <div className="flex justify-end">
+ <button
+ type="button"
+ className="py-2 px-3 text-sm font-medium text-center text-white bg-red-600 rounded-lg hover:bg-red-700 focus:ring-4 focus:outline-none focus:ring-red-300 dark:bg-red-500 dark:hover:bg-red-600 dark:focus:ring-red-900"
+ onClick={handleYes}
+ >
+ Create
+ </button>
+ </div>
+ </div>
+ </div>
+ </form>
+ </div>
+ );
+}
diff --git a/src/client/src/components/(playground)/header.tsx b/src/client/src/components/(playground)/header.tsx
index 5492270a..3963298a 100644
--- a/src/client/src/components/(playground)/header.tsx
+++ b/src/client/src/components/(playground)/header.tsx
@@ -5,8 +5,8 @@ export default function Header() {
const pathname = usePathname();
return (
<div className="relative flex shrink-0 p-2 mb-2">
- <div className="flex flex-1 overflow-y-auto capitalize text-xl">
- {pathname.substring(1)}
+ <div className="flex flex-1 overflow-y-auto uppercase text-xl">
+ {pathname.substring(1).replaceAll("-", " ")}
</div>
</div>
);
diff --git a/src/client/src/components/(playground)/sidebar.tsx b/src/client/src/components/(playground)/sidebar.tsx
index 0bd8a8c6..83adbde6 100644
--- a/src/client/src/components/(playground)/sidebar.tsx
+++ b/src/client/src/components/(playground)/sidebar.tsx
@@ -6,6 +6,7 @@ import {
ArrowLeftCircleIcon,
CircleStackIcon,
HomeModernIcon,
+ KeyIcon,
} from "@heroicons/react/24/solid";
import Image from "next/image";
import { usePathname } from "next/navigation";
@@ -32,6 +33,11 @@ const SIDEBAR_ITEMS = [
text: "Requests",
link: "/requests",
},
+ {
+ icon: <KeyIcon className={ICON_CLASSES} />,
+ text: "API keys",
+ link: "/api-keys",
+ },
{
icon: <ArrowLeftCircleIcon className={ICON_CLASSES} />,
text: "Signout",
diff --git a/src/client/src/components/common/confirmation-modal.tsx b/src/client/src/components/common/confirmation-modal.tsx
new file mode 100644
index 00000000..6fa08ac8
--- /dev/null
+++ b/src/client/src/components/common/confirmation-modal.tsx
@@ -0,0 +1,43 @@
+import { XCircleIcon } from "@heroicons/react/24/outline";
+
+type ConfirmationModalProps = {
+ handleYes: () => void;
+ handleNo: () => void;
+};
+
+export default function ConfirmationModal(props: ConfirmationModalProps) {
+ return (
+ <div className="overflow-y-auto overflow-x-hidden fixed top-0 right-0 left-0 z-50 flex justify-center items-center w-full h-full bg-gray-900/[.6]">
+ <div className="relative p-4 w-full max-w-md h-full md:h-auto">
+ <div className="relative p-4 text-center bg-white rounded-lg shadow dark:bg-gray-800 sm:p-5">
+ <button
+ type="button"
+ className="text-gray-400 absolute top-2.5 right-2.5 bg-transparent hover:bg-gray-200 hover:text-gray-900 rounded-lg text-sm p-1.5 ml-auto inline-flex items-center dark:hover:bg-gray-600 dark:hover:text-white"
+ onClick={props.handleNo}
+ >
+ <XCircleIcon className="w-5" />
+ </button>
+ <p className="mb-4 text-gray-500 dark:text-gray-300">
+ Are you sure you want to delete this item?
+ </p>
+ <div className="flex justify-center items-center space-x-4">
+ <button
+ type="button"
+ className="py-2 px-3 text-sm font-medium text-gray-500 bg-white rounded-lg border border-gray-200 hover:bg-gray-100 focus:ring-4 focus:outline-none focus:ring-primary-300 hover:text-gray-900 focus:z-10 dark:bg-gray-700 dark:text-gray-300 dark:border-gray-500 dark:hover:text-white dark:hover:bg-gray-600 dark:focus:ring-gray-600"
+ onClick={props.handleNo}
+ >
+ No, cancel
+ </button>
+ <button
+ type="button"
+ className="py-2 px-3 text-sm font-medium text-center text-white bg-red-600 rounded-lg hover:bg-red-700 focus:ring-4 focus:outline-none focus:ring-red-300 dark:bg-red-500 dark:hover:bg-red-600 dark:focus:ring-red-900"
+ onClick={props.handleYes}
+ >
+ Yes, I&apos;m sure
+ </button>
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/src/client/src/lib/api-key.ts b/src/client/src/lib/api-key.ts
new file mode 100644
index 00000000..b2a31fdf
--- /dev/null
+++ b/src/client/src/lib/api-key.ts
@@ -0,0 +1,29 @@
+import crypto from "crypto";
+import prisma from "./prisma";
+import asaw from "@/utils/asaw";
+import { normalizeAPIKeys } from "@/utils/api-key";
+
+type GenerateAPIKeyProps = {
+ name: string;
+};
+
+export async function generateAPIKey(params: GenerateAPIKeyProps) {
+ const api_key = crypto.randomBytes(32).toString("hex");
+ return await asaw(
+ prisma.apikey.create({
+ data: {
+ name: params.name,
+ api_key,
+ },
+ })
+ );
+}
+
+export async function getAPIKeys() {
+ const [, data] = await asaw(prisma.apikey.findMany());
+ return normalizeAPIKeys(data);
+}
+
+export async function deleteAPIKey(id: number) {
+ return await asaw(prisma.apikey.delete({ where: { id } }));
+}
diff --git a/src/client/src/utils/api-key.ts b/src/client/src/utils/api-key.ts
new file mode 100644
index 00000000..65fdd667
--- /dev/null
+++ b/src/client/src/utils/api-key.ts
@@ -0,0 +1,10 @@
+import { apikey } from "@prisma/client";
+
+export function maskingKey(key: string) {
+ return key.slice(0, 3) + "..." + key.slice(-3);
+}
+
+export function normalizeAPIKeys(params: apikey[] | null | undefined) {
+ if (params?.length)
+ return params.map((p) => ({ ...p, api_key: maskingKey(p.api_key) }));
+}
diff --git a/src/client/src/utils/api.ts b/src/client/src/utils/api.ts
index ba5c0f13..faa40472 100644
--- a/src/client/src/utils/api.ts
+++ b/src/client/src/utils/api.ts
@@ -1,5 +1,5 @@
type GET_DATA = {
- body: string;
+ body?: string;
method?: "GET" | "POST";
url: string;
};
@@ -13,3 +13,16 @@ export async function getData({ body, method = "POST", url }: GET_DATA) {
return res.json();
}
+
+type DELETE_DATA = {
+ url: string;
+};
+export async function deleteData({ url }: DELETE_DATA) {
+ const res = await fetch(url, { method: "DELETE" });
+ if (!res.ok) {
+ // This will activate the closest `error.js` Error Boundary
+ throw new Error("Failed to delete data");
+ }
+
+ return res.json();
+}