- Updated all packages to latest versions (React 19, Next.js 14.2.32) - Replaced sqlite3 with pg and drizzle-orm dependencies - Created complete PostgreSQL schema with relationships and indexes - Migrated all API endpoints from SQLite to Drizzle queries - Added database seeding with sample data - Updated authentication to use bcrypt instead of pbkdf2 - Configured connection pooling for PostgreSQL - Updated app version to 1.0.0 - All endpoints tested and working correctly
78 lines
2.3 KiB
TypeScript
78 lines
2.3 KiB
TypeScript
import type { NextApiRequest, NextApiResponse } from "next"
|
|
import { db, schema } from '../../../lib/db/connection'
|
|
import { desc, eq } from 'drizzle-orm'
|
|
import { generateApiKey, hashApiKey } from "../../../lib/api-auth"
|
|
|
|
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
|
try {
|
|
if (req.method === "GET") {
|
|
const keys = await db
|
|
.select({
|
|
id: schema.apiKeys.id,
|
|
name: schema.apiKeys.name,
|
|
permissions: schema.apiKeys.permissions,
|
|
rateLimit: schema.apiKeys.rateLimit,
|
|
isActive: schema.apiKeys.isActive,
|
|
lastUsed: schema.apiKeys.lastUsed,
|
|
createdAt: schema.apiKeys.createdAt
|
|
})
|
|
.from(schema.apiKeys)
|
|
.orderBy(desc(schema.apiKeys.createdAt))
|
|
|
|
res.json({
|
|
keys: keys.map(key => ({
|
|
...key,
|
|
permissions: key.permissions ? JSON.parse(key.permissions) : [],
|
|
key_preview: '***...' + (key.id.toString().slice(-4))
|
|
}))
|
|
})
|
|
|
|
} else if (req.method === "POST") {
|
|
const { name, permissions = [], rate_limit = 1000 } = req.body
|
|
|
|
if (!name) {
|
|
return res.status(400).json({ error: "Name required" })
|
|
}
|
|
|
|
const apiKey = generateApiKey()
|
|
const keyHash = hashApiKey(apiKey)
|
|
|
|
const [result] = await db
|
|
.insert(schema.apiKeys)
|
|
.values({
|
|
keyHash: keyHash,
|
|
name: name,
|
|
permissions: JSON.stringify(permissions),
|
|
rateLimit: rate_limit,
|
|
isActive: true
|
|
})
|
|
.returning({ id: schema.apiKeys.id })
|
|
|
|
res.json({
|
|
success: true,
|
|
id: result.id,
|
|
api_key: apiKey, // Only returned once during creation
|
|
name,
|
|
permissions,
|
|
rate_limit
|
|
})
|
|
|
|
} else if (req.method === "DELETE") {
|
|
const { id } = req.query
|
|
|
|
await db
|
|
.update(schema.apiKeys)
|
|
.set({ isActive: false })
|
|
.where(eq(schema.apiKeys.id, parseInt(id as string)))
|
|
|
|
res.json({ success: true })
|
|
|
|
} else {
|
|
res.status(405).json({ error: "Method not allowed" })
|
|
}
|
|
|
|
} catch (error) {
|
|
console.error('API keys error:', error)
|
|
res.status(500).json({ error: "Operation failed" })
|
|
}
|
|
} |