hermes-web/app/settings/api/keys/page.tsx

93 lines
3.1 KiB
TypeScript

"use client";
import axios from "axios";
import { Button } from "@/components/ui/button";
import * as React from 'react';
import { ApiKey, User } from "@prisma/client";
import { useEffect, useState } from "react";
import { useSession } from "next-auth/react";
import { Table, TableBody, TableCaption, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
const SettingsPage = () => {
const { data: session, status } = useSession();
const [apiKeyViewable, setApiKeyViewable] = useState(0)
const [apiKeyChanges, setApiKeyChanges] = useState(0)
const [apiKeys, setApiKeys] = useState<ApiKey[]>([])
useEffect(() => {
const fetchData = async () => {
try {
const keys = (await axios.get("/api/tokens")).data ?? {};
setApiKeys(keys)
} catch (error) {
console.log("ERROR", error)
}
};
fetchData().catch(console.error);
}, [apiKeyChanges]);
const onApiKeyAdd = async () => {
try {
await axios.post("/api/token", {
label: "Key label"
});
setApiKeyChanges(apiKeyChanges + 1)
} catch (error) {
console.log("ERROR", error)
}
}
const onApiKeyDelete = async (id: string) => {
try {
await axios.delete("/api/token/" + id);
setApiKeyChanges(apiKeyChanges - 1)
} catch (error) {
console.log("ERROR", error)
}
}
return (
<div>
<div className="px-10 py-5 mx-5 my-10">
<div>
<div className="text-xl justify-left mt-10">API Keys</div>
<Table className="max-w-2xl">
<TableCaption>A list of your secret API keys.</TableCaption>
<TableHeader>
<TableRow>
<TableHead>Label</TableHead>
<TableHead>Token</TableHead>
<TableHead>View</TableHead>
<TableHead>Action</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{apiKeys.map((key, index) => (
<TableRow key={key.id}>
<TableCell className="font-medium">{key.label}</TableCell>
<TableCell>{(apiKeyViewable & (1 << index)) > 0 ? key.id : "*".repeat(key.id.length)}</TableCell>
<TableCell>
<Button onClick={() => setApiKeyViewable((v) => v ^ (1 << index))}>
{(apiKeyViewable & (1 << index)) > 0 ? "HIDE" : "VIEW"}
</Button>
</TableCell>
<TableCell><Button onClick={() => onApiKeyDelete(key.id)}>DEL</Button></TableCell>
</TableRow>
))}
<TableRow key="ADD">
<TableCell className="font-medium"></TableCell>
<TableCell></TableCell>
<TableCell></TableCell>
<TableCell><Button onClick={onApiKeyAdd}>ADD</Button></TableCell>
</TableRow>
</TableBody>
</Table>
</div>
</div>
</div>
);
}
export default SettingsPage;