Skip to content

Commit fb9faec

Browse files
committed
Api Keys endpoint
1 parent d9a12e0 commit fb9faec

1 file changed

Lines changed: 52 additions & 0 deletions

File tree

pages/api/public/v1/admin/keys.ts

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
import type { NextApiRequest, NextApiResponse } from "next"
2+
import prisma from "@/utils/database"
3+
4+
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
5+
if (req.method !== "GET") return res.status(405).json({ success: false, error: "Method not allowed" })
6+
7+
const apiKey = req.headers.authorization?.replace("Bearer ", "")
8+
if (!apiKey) return res.status(401).json({ success: false, error: "Missing API key" })
9+
10+
try {
11+
const key = await prisma.apiKey.findUnique({
12+
where: { key: apiKey },
13+
include: {
14+
createdBy: {
15+
include: {
16+
workspaceMemberships: true
17+
}
18+
}
19+
}
20+
})
21+
22+
if (!key) return res.status(401).json({ success: false, error: "Invalid API key" })
23+
if (key.expiresAt && new Date() > key.expiresAt) {
24+
return res.status(401).json({ success: false, error: "API key expired" })
25+
}
26+
27+
const membership = key.createdBy.workspaceMemberships.find(
28+
(m) => m.workspaceGroupId === key.workspaceGroupId
29+
)
30+
const isAdmin = membership?.isAdmin ?? false
31+
32+
await prisma.apiKey.update({
33+
where: { id: key.id },
34+
data: { lastUsed: new Date() },
35+
})
36+
37+
const keys = await prisma.apiKey.findMany({
38+
where: { workspaceGroupId: key.workspaceGroupId }
39+
})
40+
41+
const sanitizedKeys = keys.map((k) => ({
42+
...k,
43+
key: isAdmin ? k.key : k.key.slice(0, 8) + "••••••••••••••••••••",
44+
createdById: k.createdById.toString(),
45+
}))
46+
47+
return res.status(200).json({ success: true, data: sanitizedKeys })
48+
} catch (error) {
49+
console.error("Error in public API:", error)
50+
return res.status(500).json({ success: false, error: "Internal server error" })
51+
}
52+
}

0 commit comments

Comments
 (0)