48 lines
1.0 KiB
TypeScript
48 lines
1.0 KiB
TypeScript
import crypto from "crypto";
|
|
import { db } from "@/lib/db";
|
|
import { claws } 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 = `claw:key:${apiKey}`;
|
|
const cachedClawId = await redis.get(cacheKey);
|
|
|
|
if (cachedClawId) {
|
|
const claw = await db
|
|
.select()
|
|
.from(claws)
|
|
.where(eq(claws.id, cachedClawId))
|
|
.limit(1);
|
|
|
|
if (claw.length > 0) {
|
|
return claw[0];
|
|
}
|
|
}
|
|
|
|
const claw = await db
|
|
.select()
|
|
.from(claws)
|
|
.where(eq(claws.apiKey, apiKey))
|
|
.limit(1);
|
|
|
|
if (claw.length === 0) {
|
|
return null;
|
|
}
|
|
|
|
await redis.set(cacheKey, claw[0].id, "EX", API_KEY_CACHE_TTL);
|
|
|
|
return claw[0];
|
|
} catch (error) {
|
|
console.error("Failed to validate API key:", error);
|
|
return null;
|
|
}
|
|
}
|