This commit is contained in:
richarjiang
2026-03-13 11:00:01 +08:00
commit fa4c458eda
51 changed files with 8843 additions and 0 deletions

47
lib/auth/api-key.ts Normal file
View File

@@ -0,0 +1,47 @@
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;
}
}