import crypto from "crypto"; import { db } from "@/lib/db"; import { lobsters } from "@/lib/db/schema"; import { eq } from "drizzle-orm"; import { redis } from "@/lib/redis"; const API_KEY_CACHE_TTL = 3600; // 1 hour in seconds export function generateApiKey(): string { return crypto.randomBytes(32).toString("hex"); } export async function validateApiKey(apiKey: string) { try { const cacheKey = `lobster:key:${apiKey}`; const cachedLobsterId = await redis.get(cacheKey); if (cachedLobsterId) { const lobster = await db .select() .from(lobsters) .where(eq(lobsters.id, cachedLobsterId)) .limit(1); if (lobster.length > 0) { return lobster[0]; } } const lobster = await db .select() .from(lobsters) .where(eq(lobsters.apiKey, apiKey)) .limit(1); if (lobster.length === 0) { return null; } await redis.set(cacheKey, lobster[0].id, "EX", API_KEY_CACHE_TTL); return lobster[0]; } catch (error) { console.error("Failed to validate API key:", error); return null; } }