Files
openclaw-market/lib/auth/api-key.ts
richarjiang fa4c458eda init
2026-03-13 11:00:01 +08:00

48 lines
1.1 KiB
TypeScript

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;
}
}