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((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((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() } }