migrate from SQLite to PostgreSQL with Drizzle ORM
- 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
This commit is contained in:
@@ -1,31 +1,26 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next"
|
||||
import sqlite3 from "sqlite3"
|
||||
import path from "path"
|
||||
import crypto from "crypto"
|
||||
import { db, schema } from "../../../lib/db/connection"
|
||||
import { eq, count, sql } from "drizzle-orm"
|
||||
import * as bcrypt from "bcryptjs"
|
||||
|
||||
function hashPassword(password: string): { hash: string, salt: string } {
|
||||
const salt = crypto.randomBytes(32).toString('hex')
|
||||
const hash = crypto.pbkdf2Sync(password, salt, 10000, 64, 'sha256').toString('hex')
|
||||
return { hash, salt }
|
||||
async function hashPassword(password: string): Promise<string> {
|
||||
return await bcrypt.hash(password, 12)
|
||||
}
|
||||
|
||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
const dbPath = path.join(process.cwd(), "database", "antihoax.db")
|
||||
const db = new sqlite3.Database(dbPath)
|
||||
|
||||
try {
|
||||
if (req.method === "GET") {
|
||||
const users = await new Promise<any[]>((resolve, reject) => {
|
||||
db.all(
|
||||
`SELECT id, email, role, is_active, created_at, last_login,
|
||||
(SELECT COUNT(*) FROM sources WHERE moderator_id = users.id) as sources_moderated
|
||||
FROM users ORDER BY created_at DESC`,
|
||||
(err, rows) => {
|
||||
if (err) reject(err)
|
||||
else resolve(rows)
|
||||
}
|
||||
)
|
||||
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 })
|
||||
|
||||
@@ -40,27 +35,25 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
|
||||
return res.status(400).json({ error: "Invalid role" })
|
||||
}
|
||||
|
||||
const { hash, salt } = hashPassword(password)
|
||||
const passwordHash = await hashPassword(password)
|
||||
|
||||
const result = await new Promise<any>((resolve, reject) => {
|
||||
db.run(
|
||||
`INSERT INTO users (email, password_hash, salt, role, is_active, created_at)
|
||||
VALUES (?, ?, ?, ?, 1, datetime('now'))`,
|
||||
[email, hash, salt, role],
|
||||
function(err) {
|
||||
if (err) reject(err)
|
||||
else resolve({ id: this.lastID })
|
||||
}
|
||||
)
|
||||
})
|
||||
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.id,
|
||||
id: result[0].id,
|
||||
email,
|
||||
role,
|
||||
is_active: true
|
||||
isActive: true
|
||||
}
|
||||
})
|
||||
|
||||
@@ -70,12 +63,10 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
|
||||
|
||||
} catch (error: any) {
|
||||
console.error('Users API error:', error)
|
||||
if (error?.code === 'SQLITE_CONSTRAINT_UNIQUE') {
|
||||
if (error?.code === '23505') {
|
||||
res.status(400).json({ error: "User already exists" })
|
||||
} else {
|
||||
res.status(500).json({ error: "Operation failed" })
|
||||
}
|
||||
} finally {
|
||||
db.close()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user