Files
ims/app/api/dashboard/export/route.ts
T
adminandClaude Sonnet 4.6 8fe036bc1a fix: P2 API hardening — unbounded SELECTs, export audit log, header injection, empty-key guard
- export: add .limit(10000), sanitize filename, write_audit_log on every export
- stats: add .limit(10000) to aggregation query
- settings POST: reject empty string values to prevent silent key deletion

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CPf5Rc8QPx6V8KLEEgfKEQ
2026-07-12 21:25:35 +08:00

80 lines
2.7 KiB
TypeScript

export const dynamic = 'force-dynamic'
import { NextRequest, NextResponse } from 'next/server'
import { createClient } from '@/lib/supabase/server'
import { rowsToCsv } from '@/lib/csv'
export async function GET(request: NextRequest) {
const supabase = await createClient()
const { data: { user }, error: authError } = await supabase.auth.getUser()
if (authError || !user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
const { data: profile } = await supabase.from('users').select('role').eq('id', user.id).single()
if (!profile) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
const role = request.nextUrl.searchParams.get('role') ?? 'hse'
const allowedRoles: Record<string, string[]> = {
hse: ['hse', 'admin'],
management: ['management', 'admin'],
}
if (!allowedRoles[role] || !allowedRoles[role].includes(profile.role)) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
}
const { data: incidents } = await supabase
.from('incidents')
.select(`
reference_no, incident_type, status, severity, reported_at, closed_at,
injury_involved, medical_status, lost_days,
sites (name), zones (name)
`)
.order('reported_at', { ascending: false })
.limit(10000)
const rows = incidents ?? []
const headers = [
'Reference', 'Type', 'Status', 'Severity', 'Site', 'Zone',
'Reported At', 'Closed At', 'Injury Involved', 'Medical Status', 'Lost Days',
]
const csvRows = rows.map(inc => {
const siteName = (inc.sites as unknown as { name: string } | null)?.name ?? ''
const zoneName = (inc.zones as unknown as { name: string } | null)?.name ?? ''
return [
inc.reference_no ?? '',
inc.incident_type,
inc.status,
String(inc.severity ?? ''),
siteName,
zoneName,
inc.reported_at ? new Date(inc.reported_at as string).toISOString().split('T')[0] : '',
inc.closed_at ? new Date(inc.closed_at as string).toISOString().split('T')[0] : '',
inc.injury_involved ? 'Yes' : 'No',
inc.medical_status ?? '',
String(inc.lost_days ?? ''),
]
})
const csv = rowsToCsv(headers, csvRows)
const safeRole = role.replace(/[^a-z0-9]/gi, '')
const filename = `incidents-${safeRole}-${new Date().toISOString().split('T')[0]}.csv`
await supabase.rpc('write_audit_log', {
p_table_name: 'incidents',
p_record_id: user.id,
p_action: 'export_csv',
p_new_value: { role, row_count: rows.length } as never,
})
return new NextResponse(csv, {
status: 200,
headers: {
'Content-Type': 'text/csv; charset=utf-8',
'Content-Disposition': `attachment; filename="${filename}"`,
},
})
}