Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Api keys #74

Merged
merged 9 commits into from
Jun 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions next.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,27 @@ const config = {
},
],
},

async headers() {
return [
{
source: "/api/:path*",
headers: [
{ key: "Access-Control-Allow-Credentials", value: "true" },
{ key: "Access-Control-Allow-Origin", value: "*" },
{
key: "Access-Control-Allow-Methods",
value: "GET,OPTIONS,PATCH,DELETE,POST,PUT",
},
{
key: "Access-Control-Allow-Headers",
value:
"X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version",
},
],
},
];
},
};

export default config;
9 changes: 9 additions & 0 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -120,3 +120,12 @@ model Comment {
roundId String
round Round @relation(fields: [roundId], references: [id])
}


model ApiKey {
id String @id @default(cuid())
key String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
creatorId String
}
7 changes: 7 additions & 0 deletions src/features/admin/layouts/AdminLayout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
ChevronLeft,
Coins,
Files,
KeyRound,
Pencil,
Settings2,
ShieldCheck,
Expand Down Expand Up @@ -104,6 +105,12 @@ function RoundConfigSidebar() {
icon: Coins,
href: `/${domain}/admin/distribute`,
},
{
children: "API Keys",
description: "Integrate external services",
icon: KeyRound,
href: `/${domain}/admin/api-keys`,
},
];
return (
<div className="space-y-1">
Expand Down
119 changes: 119 additions & 0 deletions src/pages/[domain]/admin/api-keys/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
import { format } from "date-fns";
import { Clock, Trash } from "lucide-react";
import { Alert } from "~/components/ui/Alert";
import { Button } from "~/components/ui/Button";
import { Divider } from "~/components/ui/Divider";
import { FormSection } from "~/components/ui/Form";
import { Markdown } from "~/components/ui/Markdown";
import { RoundAdminLayout } from "~/features/admin/layouts/AdminLayout";
import { Layout } from "~/layouts/DefaultLayout";
import { api } from "~/utils/api";

export default function ApiKeysPage() {
return (
<RoundAdminLayout>
{() => (
<div>
<ApiKeys />
</div>
)}
</RoundAdminLayout>
);
}

function ApiKeys() {
const keys = api.apiKeys.list.useQuery();

const utils = api.useUtils();
const onSuccess = () => utils.apiKeys.invalidate();

const createKey = api.apiKeys.create.useMutation({ onSuccess });
const deleteKey = api.apiKeys.delete.useMutation({ onSuccess });

const { data, isPending } = api.apiKeys.list.useQuery();
if (isPending) return <div>loading...</div>;
console.log(data);
return (
<FormSection
title="API Keys"
description="Create and manage API keys to integrate external pages. You can use these to fetch data about applications and projects."
>
{createKey.data && (
<div className="mb-2">
API key created. Copy and store this in a safe place.
<Markdown>
{`\`\`\`
${createKey.data?.key}
\`\`\``}
</Markdown>
</div>
)}
{keys.data && (
<div className="mb-2 space-y-2 divide-y rounded border">
{!keys.isPending && !keys.data?.length && (
<div className="p-4 text-center text-gray-500">
You haven't created any API keys yet
</div>
)}
{keys.data?.map((key) => (
<div
key={key.id}
className="flex items-center justify-between p-4"
>
<div>
<pre>{key.id}</pre>
<div className="flex items-center gap-1 text-sm">
<Clock className="size-3" />
{format(key.createdAt, "PPP")}
</div>
</div>

<Button
icon={Trash}
isLoading={
deleteKey.variables?.id === key.id && deleteKey.isPending
}
onClick={() => deleteKey.mutate({ id: key.id })}
/>
</div>
))}
</div>
)}
<Button
isLoading={createKey.isPending}
onClick={() => createKey.mutate()}
>
Create API key
</Button>

<Divider className={"my-8"} />

<Markdown>
{`
\`\`\`tsx
// Example
const input = JSON.stringify({ json: {}})
await fetch("https://easyretropgf.xyz/api/trpc/projects.search?input=" + encodeURIComponent(input), {
headers: {
"content-type": "application/json",
"round-id": "<your round id>"
"x-api-key": "<api key>"
}
}).then(res => res.json())

\`\`\`
`}
</Markdown>
</FormSection>
);
}

function CreateApiKey() {
const { data, mutate, isPending } = api.apiKeys.create.useMutation();
console.log("data", data);
return (
<Button isLoading={isPending} onClick={() => mutate()}>
Create API Key
</Button>
);
}
2 changes: 2 additions & 0 deletions src/server/api/root.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { apiKeysRouter } from "~/server/api/routers/apiKeys";
import { ballotRouter } from "~/server/api/routers/ballot";
import { resultsRouter } from "~/server/api/routers/results";
import { roundsRouter } from "~/server/api/routers/rounds";
Expand All @@ -16,6 +17,7 @@ import { createTRPCRouter } from "~/server/api/trpc";
* All routers added in /api/routers should be manually added here.
*/
export const appRouter = createTRPCRouter({
apiKeys: apiKeysRouter,
rounds: roundsRouter,
comments: commentsRouter,
results: resultsRouter,
Expand Down
36 changes: 36 additions & 0 deletions src/server/api/routers/apiKeys.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { createHash } from "crypto";
import { z } from "zod";
import { adminProcedure, createTRPCRouter } from "~/server/api/trpc";
import { hashApiKey } from "~/utils/hashApiKey";

const genApiKey = () => hashApiKey(crypto.randomUUID());

export const apiKeysRouter = createTRPCRouter({
get: adminProcedure
.input(z.object({ id: z.string() }))
.query(async ({ ctx, input: { id } }) => {
const creatorId = ctx.session?.user.name!;
return ctx.db.apiKey.findFirst({ where: { id, creatorId } });
}),
list: adminProcedure.query(async ({ ctx }) => {
const creatorId = ctx.session?.user.name!;
return ctx.db.apiKey.findMany({ where: { creatorId } });
}),
delete: adminProcedure
.input(z.object({ id: z.string() }))
.mutation(async ({ ctx, input: { id } }) => {
const creatorId = ctx.session?.user.name!;
return ctx.db.apiKey.delete({ where: { id, creatorId } });
}),
create: adminProcedure.mutation(async ({ ctx }) => {
const key = genApiKey();

const creatorId = ctx.session?.user.name!;

await ctx.db.apiKey.create({
data: { creatorId, key: hashApiKey(key) },
});

return { key };
}),
});
24 changes: 16 additions & 8 deletions src/server/api/trpc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import {
type AttestationFetcher,
createAttestationFetcher,
} from "~/utils/fetchAttestations";
import { hashApiKey } from "~/utils/hashApiKey";

/**
* 1. CONTEXT
Expand Down Expand Up @@ -78,13 +79,9 @@ export const createTRPCContext = async (opts: CreateNextContextOptions) => {
const session = await getServerAuthSession({ req, res });

// Get the current round domain
const domain = req.headers.referer?.split("/")[3];
const domain = req.headers["round-id"] as string;

return createInnerTRPCContext({
session,
res,
domain,
});
return createInnerTRPCContext({ session, res, domain });
};

/**
Expand Down Expand Up @@ -205,12 +202,23 @@ const enforceUserIsAdmin = t.middleware(({ ctx, next }) => {
*/

export const protectedProcedure = t.procedure.use(enforceUserIsAuthed);
export const roundProcedure = publicProcedure.use(roundMiddleware);
export const protectedRoundProcedure = publicProcedure
export const roundProcedure = t.procedure.use(roundMiddleware);
export const protectedRoundProcedure = t.procedure
.use(roundMiddleware)
.use(enforceUserIsAuthed);
export const adminProcedure = protectedProcedure
.use(roundMiddleware)
.use(enforceUserIsAdmin);

export const attestationProcedure = roundProcedure.use(attestationMiddleware);

export async function getApiKeySession(apiKey?: string | null) {
if (!apiKey) return null;

// Find API key
const key = await db.apiKey.findFirst({ where: { key: hashApiKey(apiKey) } });

if (key?.creatorId) return { id: key.creatorId };

return null;
}
5 changes: 5 additions & 0 deletions src/utils/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ export const api = createTRPCNext<AppRouter>({
*
* @see https://trpc.io/docs/links
*/

links: [
loggerLink({
enabled: (opts) =>
Expand All @@ -35,6 +36,10 @@ export const api = createTRPCNext<AppRouter>({
httpBatchLink({
transformer: superjson,
url: `${getBaseUrl()}/api/trpc`,
headers() {
const roundId = location.pathname.split("/")[1];
return { "round-id": roundId };
},
}),
],
};
Expand Down
5 changes: 5 additions & 0 deletions src/utils/hashApiKey.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { createHash } from "crypto";

export function hashApiKey(apiKey: string) {
return createHash("sha256").update(apiKey).digest("hex");
}