Files
ims/app/api/dashboard/stats/route.ts
T
adminandClaude Sonnet 4.6 16dd62df11 fix: P1 API security hardening — rate limits, auth guards, duplicate prevention
- verify/route.ts: setDate → setUTCDate to avoid timezone off-by-one on recheck date
- triage-suggest, rca-draft, quality-check: 60s per-user rate limit via audit_log
- quality-check: add write_audit_log (was missing, CLAUDE.md violation)
- investigation POST: 409 if investigation already exists for incident
- incidents POST: 60s per-user rate limit via audit_log
- addenda GET: restrict to hse/admin/supervisor roles
- dashboard/stats GET: restrict to hse/admin/management roles

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

41 lines
1.5 KiB
TypeScript

export const dynamic = 'force-dynamic'
import { NextResponse } from 'next/server'
import { createClient } from '@/lib/supabase/server'
export async function GET() {
const supabase = await createClient()
const { data: { user } } = await supabase.auth.getUser()
if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
const { data: profile } = await supabase.from('users').select('role').eq('id', user.id).single()
if (!profile || !['hse', 'admin', 'management'].includes(profile.role))
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
const { data: incidents, error } = await supabase
.from('incidents')
.select('id, status, incident_type, sites (name)')
if (error) return NextResponse.json({ error: 'Failed to fetch stats' }, { status: 500 })
const rows = incidents ?? []
const total = rows.length
const closed = rows.filter(r => r.status === 'closed').length
const open = total - closed
const by_type: Record<string, number> = {}
for (const r of rows) {
by_type[r.incident_type] = (by_type[r.incident_type] ?? 0) + 1
}
const siteMap: Record<string, number> = {}
for (const r of rows) {
const name = (r.sites as unknown as { name: string } | null)?.name ?? 'Unknown'
siteMap[name] = (siteMap[name] ?? 0) + 1
}
const by_site = Object.entries(siteMap).map(([name, count]) => ({ name, count }))
.sort((a, b) => b.count - a.count)
return NextResponse.json({ total, open, closed, by_type, by_site })
}