user management and authentication system
This commit is contained in:
81
pages/api/admin/users.ts
Normal file
81
pages/api/admin/users.ts
Normal file
@@ -0,0 +1,81 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next"
|
||||
import sqlite3 from "sqlite3"
|
||||
import path from "path"
|
||||
import crypto from "crypto"
|
||||
|
||||
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 }
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
)
|
||||
})
|
||||
|
||||
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 { hash, salt } = 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 })
|
||||
}
|
||||
)
|
||||
})
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
user: {
|
||||
id: result.id,
|
||||
email,
|
||||
role,
|
||||
is_active: true
|
||||
}
|
||||
})
|
||||
|
||||
} else {
|
||||
res.status(405).json({ error: "Method not allowed" })
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('Users API error:', error)
|
||||
if (error.code === 'SQLITE_CONSTRAINT_UNIQUE') {
|
||||
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