|
| 1 | +import { createHash, randomBytes } from "node:crypto"; |
| 2 | +import { eq } from "drizzle-orm"; |
| 3 | +import { NextResponse } from "next/server"; |
| 4 | +import { auth } from "@/lib/auth"; |
| 5 | +import { db } from "@/lib/db"; |
| 6 | +import { apiKeys } from "@/lib/db/schema"; |
| 7 | + |
| 8 | +// Generate a secure API key |
| 9 | +function generateApiKey(): { key: string; hash: string; prefix: string } { |
| 10 | + const randomPart = randomBytes(24).toString("base64url"); |
| 11 | + const key = `wfb_${randomPart}`; |
| 12 | + const hash = createHash("sha256").update(key).digest("hex"); |
| 13 | + const prefix = key.slice(0, 11); // "wfb_" + first 7 chars |
| 14 | + return { key, hash, prefix }; |
| 15 | +} |
| 16 | + |
| 17 | +// GET - List all API keys for the current user |
| 18 | +export async function GET(request: Request) { |
| 19 | + try { |
| 20 | + const session = await auth.api.getSession({ |
| 21 | + headers: request.headers, |
| 22 | + }); |
| 23 | + |
| 24 | + if (!session?.user) { |
| 25 | + return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); |
| 26 | + } |
| 27 | + |
| 28 | + const keys = await db.query.apiKeys.findMany({ |
| 29 | + where: eq(apiKeys.userId, session.user.id), |
| 30 | + columns: { |
| 31 | + id: true, |
| 32 | + name: true, |
| 33 | + keyPrefix: true, |
| 34 | + createdAt: true, |
| 35 | + lastUsedAt: true, |
| 36 | + }, |
| 37 | + orderBy: (table, { desc }) => [desc(table.createdAt)], |
| 38 | + }); |
| 39 | + |
| 40 | + return NextResponse.json(keys); |
| 41 | + } catch (error) { |
| 42 | + console.error("Failed to list API keys:", error); |
| 43 | + return NextResponse.json( |
| 44 | + { error: "Failed to list API keys" }, |
| 45 | + { status: 500 } |
| 46 | + ); |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +// POST - Create a new API key |
| 51 | +export async function POST(request: Request) { |
| 52 | + try { |
| 53 | + const session = await auth.api.getSession({ |
| 54 | + headers: request.headers, |
| 55 | + }); |
| 56 | + |
| 57 | + if (!session?.user) { |
| 58 | + return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); |
| 59 | + } |
| 60 | + |
| 61 | + // Check if user is anonymous |
| 62 | + const isAnonymous = |
| 63 | + session.user.name === "Anonymous" || |
| 64 | + session.user.email?.startsWith("temp-"); |
| 65 | + |
| 66 | + if (isAnonymous) { |
| 67 | + return NextResponse.json( |
| 68 | + { error: "Anonymous users cannot create API keys" }, |
| 69 | + { status: 403 } |
| 70 | + ); |
| 71 | + } |
| 72 | + |
| 73 | + const body = await request.json().catch(() => ({})); |
| 74 | + const name = body.name || null; |
| 75 | + |
| 76 | + // Generate new API key |
| 77 | + const { key, hash, prefix } = generateApiKey(); |
| 78 | + |
| 79 | + // Save to database |
| 80 | + const [newKey] = await db |
| 81 | + .insert(apiKeys) |
| 82 | + .values({ |
| 83 | + userId: session.user.id, |
| 84 | + name, |
| 85 | + keyHash: hash, |
| 86 | + keyPrefix: prefix, |
| 87 | + }) |
| 88 | + .returning({ |
| 89 | + id: apiKeys.id, |
| 90 | + name: apiKeys.name, |
| 91 | + keyPrefix: apiKeys.keyPrefix, |
| 92 | + createdAt: apiKeys.createdAt, |
| 93 | + }); |
| 94 | + |
| 95 | + // Return the full key only on creation (won't be shown again) |
| 96 | + return NextResponse.json({ |
| 97 | + ...newKey, |
| 98 | + key, // Full key - only returned once! |
| 99 | + }); |
| 100 | + } catch (error) { |
| 101 | + console.error("Failed to create API key:", error); |
| 102 | + return NextResponse.json( |
| 103 | + { error: "Failed to create API key" }, |
| 104 | + { status: 500 } |
| 105 | + ); |
| 106 | + } |
| 107 | +} |
0 commit comments