user management and authentication system

This commit is contained in:
2024-08-20 09:14:52 +02:00
parent 1d40161f27
commit 88991c9de0
3 changed files with 332 additions and 0 deletions

81
pages/api/admin/users.ts Normal file
View 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()
}
}

75
pages/api/auth/login.ts Normal file
View File

@@ -0,0 +1,75 @@
import type { NextApiRequest, NextApiResponse } from "next"
import sqlite3 from "sqlite3"
import path from "path"
import crypto from "crypto"
function hashPassword(password: string, salt: string): string {
return crypto.pbkdf2Sync(password, salt, 10000, 64, 'sha256').toString('hex')
}
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method !== "POST") return res.status(405).json({ error: "Method not allowed" })
const { email, password } = req.body
if (!email || !password) {
return res.status(400).json({ error: "Email and password required" })
}
const dbPath = path.join(process.cwd(), "database", "antihoax.db")
const db = new sqlite3.Database(dbPath)
try {
const user = await new Promise<any>((resolve, reject) => {
db.get(
"SELECT id, email, password_hash, salt, role, is_active FROM users WHERE email = ?",
[email],
(err, row) => {
if (err) reject(err)
else resolve(row)
}
)
})
if (!user) {
return res.status(401).json({ error: "Invalid credentials" })
}
if (!user.is_active) {
return res.status(401).json({ error: "Account is disabled" })
}
const hashedPassword = hashPassword(password, user.salt)
if (hashedPassword !== user.password_hash) {
return res.status(401).json({ error: "Invalid credentials" })
}
// Update last login
await new Promise<void>((resolve, reject) => {
db.run(
"UPDATE users SET last_login = datetime('now') WHERE id = ?",
[user.id],
(err) => {
if (err) reject(err)
else resolve()
}
)
})
res.json({
success: true,
user: {
id: user.id,
email: user.email,
role: user.role
},
token: Buffer.from(`${user.id}:${Date.now()}`).toString('base64')
})
} catch (error) {
console.error('Login error:', error)
res.status(500).json({ error: "Login failed" })
} finally {
db.close()
}
}