85 lines
2.0 KiB
Go
85 lines
2.0 KiB
Go
package handlers
|
|
|
|
import (
|
|
"fmt"
|
|
"net/http"
|
|
"time"
|
|
|
|
"dip-ids/internal/report"
|
|
"dip-ids/internal/storage"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
type ReportsHandler struct {
|
|
db *storage.DB
|
|
}
|
|
|
|
func NewReportsHandler(db *storage.DB) *ReportsHandler {
|
|
return &ReportsHandler{db: db}
|
|
}
|
|
|
|
// Generate GET /api/reports/generate
|
|
func (h *ReportsHandler) Generate(c *gin.Context) {
|
|
// Собираем данные для отчёта
|
|
alerts, _, err := h.db.GetAlerts(storage.AlertFilter{PageSize: 500})
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
bySeverity, err := h.db.AlertsBySeverity()
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
byType, err := h.db.AlertsByType()
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
topIPs, err := h.db.TopSourceIPs(10)
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
trafficByProto, err := h.db.TrafficByProtocol()
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
recentStats, err := h.db.GetRecentPacketStats(100)
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
session, _ := h.db.GetLastSession()
|
|
|
|
data := report.Data{
|
|
GeneratedAt: time.Now(),
|
|
Session: session,
|
|
Alerts: alerts,
|
|
BySeverity: bySeverity,
|
|
ByType: byType,
|
|
TopIPs: topIPs,
|
|
TrafficByProto: trafficByProto,
|
|
RecentStats: recentStats,
|
|
}
|
|
|
|
pdf, err := report.Generate(data)
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
filename := fmt.Sprintf("nids-report-%s.pdf", time.Now().Format("2006-01-02_15-04"))
|
|
c.Header("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, filename))
|
|
c.Header("Content-Type", "application/pdf")
|
|
c.Data(http.StatusOK, "application/pdf", pdf)
|
|
}
|