report form
This commit is contained in:
68
pages/api/reports.ts
Normal file
68
pages/api/reports.ts
Normal file
@@ -0,0 +1,68 @@
|
||||
import type { NextApiRequest, NextApiResponse } from 'next'
|
||||
import sqlite3 from 'sqlite3'
|
||||
import path from 'path'
|
||||
|
||||
function extractDomain(url: string): string {
|
||||
try {
|
||||
const urlObj = new URL(url)
|
||||
return urlObj.hostname.replace('www.', '')
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
export default async function handler(
|
||||
req: NextApiRequest,
|
||||
res: NextApiResponse
|
||||
) {
|
||||
if (req.method !== 'POST') {
|
||||
return res.status(405).json({ error: 'Method not allowed' })
|
||||
}
|
||||
|
||||
const { source_url, reporter_email, reporter_name, description, categories } = req.body
|
||||
|
||||
if (!source_url || !description) {
|
||||
return res.status(400).json({ error: 'URL and description are required' })
|
||||
}
|
||||
|
||||
const domain = extractDomain(source_url)
|
||||
if (!domain) {
|
||||
return res.status(400).json({ error: 'Invalid URL format' })
|
||||
}
|
||||
|
||||
const dbPath = path.join(process.cwd(), 'database', 'antihoax.db')
|
||||
const db = new sqlite3.Database(dbPath)
|
||||
|
||||
try {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
db.run(
|
||||
`INSERT INTO reports (
|
||||
source_url, source_domain, reporter_email, reporter_name,
|
||||
category_suggestions, description, ip_address, user_agent
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
[
|
||||
source_url,
|
||||
domain,
|
||||
reporter_email || null,
|
||||
reporter_name || null,
|
||||
JSON.stringify(categories || []),
|
||||
description,
|
||||
req.headers['x-forwarded-for'] || req.connection.remoteAddress,
|
||||
req.headers['user-agent']
|
||||
],
|
||||
function(err) {
|
||||
if (err) reject(err)
|
||||
else resolve()
|
||||
}
|
||||
)
|
||||
})
|
||||
|
||||
return res.status(200).json({ success: true, message: 'Report submitted successfully' })
|
||||
|
||||
} catch (error) {
|
||||
console.error('Database error:', error)
|
||||
return res.status(500).json({ error: 'Internal server error' })
|
||||
} finally {
|
||||
db.close()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user