audit.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package handler
  2. import (
  3. "encoding/json"
  4. "spider/internal/model"
  5. "spider/internal/store"
  6. "github.com/gin-gonic/gin"
  7. )
  8. // AuditHandler handles audit log queries.
  9. type AuditHandler struct {
  10. store *store.Store
  11. }
  12. // List handles GET /audit-logs (admin only)
  13. func (h *AuditHandler) List(c *gin.Context) {
  14. page, pageSize, offset := parsePage(c)
  15. query := h.store.DB.Model(&model.AuditLog{})
  16. if username := c.Query("username"); username != "" {
  17. query = query.Where("username = ?", username)
  18. }
  19. if action := c.Query("action"); action != "" {
  20. query = query.Where("action = ?", action)
  21. }
  22. if targetType := c.Query("target_type"); targetType != "" {
  23. query = query.Where("target_type = ?", targetType)
  24. }
  25. if targetID := c.Query("target_id"); targetID != "" {
  26. query = query.Where("target_id = ?", targetID)
  27. }
  28. if dateFrom := c.Query("date_from"); dateFrom != "" {
  29. query = query.Where("created_at >= ?", dateFrom)
  30. }
  31. if dateTo := c.Query("date_to"); dateTo != "" {
  32. query = query.Where("created_at <= ?", dateTo)
  33. }
  34. var total int64
  35. query.Count(&total)
  36. var logs []model.AuditLog
  37. if err := query.Order("created_at DESC").Limit(pageSize).Offset(offset).Find(&logs).Error; err != nil {
  38. Fail(c, 500, err.Error())
  39. return
  40. }
  41. PageOK(c, logs, total, page, pageSize)
  42. }
  43. // LogAudit records an audit log entry asynchronously.
  44. func LogAudit(s *store.Store, c *gin.Context, action, targetType, targetID string, detail interface{}) {
  45. username := c.GetString("username")
  46. ip := c.ClientIP()
  47. var detailJSON []byte
  48. if detail != nil {
  49. detailJSON, _ = json.Marshal(detail)
  50. }
  51. log := model.AuditLog{
  52. Username: username,
  53. Action: action,
  54. TargetType: targetType,
  55. TargetID: targetID,
  56. Detail: detailJSON,
  57. IP: ip,
  58. }
  59. go s.DB.Create(&log)
  60. }