- 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
72 lines
2.1 KiB
TypeScript
72 lines
2.1 KiB
TypeScript
import type { NextApiRequest, NextApiResponse } from "next"
|
|
import { db, schema } from "../../../lib/db/connection"
|
|
import { eq, count, sql } from "drizzle-orm"
|
|
import * as bcrypt from "bcryptjs"
|
|
|
|
async function hashPassword(password: string): Promise<string> {
|
|
return await bcrypt.hash(password, 12)
|
|
}
|
|
|
|
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
|
try {
|
|
if (req.method === "GET") {
|
|
const users = await db.select({
|
|
id: schema.users.id,
|
|
email: schema.users.email,
|
|
role: schema.users.role,
|
|
isActive: schema.users.isActive,
|
|
createdAt: schema.users.createdAt,
|
|
lastLogin: schema.users.lastLogin,
|
|
sourcesModerated: sql<number>`(SELECT COUNT(*) FROM ${schema.sources} WHERE verified_by = ${schema.users.id})`
|
|
})
|
|
.from(schema.users)
|
|
.orderBy(schema.users.createdAt)
|
|
|
|
res.json({ users })
|
|
|
|
} else if (req.method === "POST") {
|
|
const { email, password, role } = req.body
|
|
|
|
if (!email || !password || !role) {
|
|
return res.status(400).json({ error: "Email, password and role required" })
|
|
}
|
|
|
|
if (!['admin', 'moderator'].includes(role)) {
|
|
return res.status(400).json({ error: "Invalid role" })
|
|
}
|
|
|
|
const passwordHash = await hashPassword(password)
|
|
|
|
const result = await db.insert(schema.users)
|
|
.values({
|
|
email,
|
|
passwordHash,
|
|
name: email.split('@')[0], // Use email username as name
|
|
role: role as 'admin' | 'moderator',
|
|
isActive: true
|
|
})
|
|
.returning({ id: schema.users.id })
|
|
|
|
res.json({
|
|
success: true,
|
|
user: {
|
|
id: result[0].id,
|
|
email,
|
|
role,
|
|
isActive: true
|
|
}
|
|
})
|
|
|
|
} else {
|
|
res.status(405).json({ error: "Method not allowed" })
|
|
}
|
|
|
|
} catch (error: any) {
|
|
console.error('Users API error:', error)
|
|
if (error?.code === '23505') {
|
|
res.status(400).json({ error: "User already exists" })
|
|
} else {
|
|
res.status(500).json({ error: "Operation failed" })
|
|
}
|
|
}
|
|
} |