wafmanage.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. package admin
  2. import (
  3. "context"
  4. v1 "github.com/go-nunu/nunu-layout-advanced/api/v1"
  5. adminApi "github.com/go-nunu/nunu-layout-advanced/api/v1/admin"
  6. "github.com/go-nunu/nunu-layout-advanced/internal/model"
  7. "github.com/go-nunu/nunu-layout-advanced/internal/repository"
  8. "math"
  9. "strings"
  10. )
  11. type WafManageRepository interface {
  12. GetWafManageList(ctx context.Context,req adminApi.WafManageList) (*v1.PaginatedResponse[adminApi.WafManageListRes], error)
  13. }
  14. func NewWafManageRepository(
  15. repository *repository.Repository,
  16. ) WafManageRepository {
  17. return &wafManageRepository{
  18. Repository: repository,
  19. }
  20. }
  21. type wafManageRepository struct {
  22. *repository.Repository
  23. }
  24. func (r *wafManageRepository) GetWafManageList(ctx context.Context,req adminApi.WafManageList) (*v1.PaginatedResponse[adminApi.WafManageListRes], error) {
  25. var res []adminApi.WafManageListRes
  26. var total int64
  27. query := r.DB(ctx).Model(&model.GlobalLimit{}).Table("shd_waf as waf")
  28. query = query.Joins("left join shd_clients as user on user.id = waf.uid")
  29. query = query.Joins("left join shd_host as host on host.id = waf.host_id")
  30. query = query.Where("waf.state = ?", 1)
  31. if req.Id > 0 {
  32. query = query.Where("waf.uid = ?", req.Id)
  33. }
  34. if req.Name != "" {
  35. trimmedName := strings.TrimSpace(req.Name)
  36. // 使用 LIKE 进行模糊匹配
  37. query = query.Where("waf.name LIKE CONCAT('%', ?, '%')", trimmedName)
  38. }
  39. if req.HostId > 0 {
  40. query = query.Where("waf.host_id = ?", req.HostId)
  41. }
  42. if req.Username != "" {
  43. trimmedName := strings.TrimSpace(req.Username)
  44. // 使用 LIKE 进行模糊匹配
  45. query = query.Where("user.username LIKE CONCAT('%', ?, '%')", trimmedName)
  46. }
  47. if !req.ExpiredAt.IsZero() {
  48. // 使用 LIKE 进行模糊匹配
  49. query = query.Where("waf.expired_at <= ?", req.ExpiredAt)
  50. }
  51. if req.Column != "" && req.Order != "" {
  52. query = query.Order(req.Column + " " + req.Order)
  53. }
  54. if err := query.Count(&total).Error; err != nil {
  55. return nil, err
  56. }
  57. page := req.Current
  58. pageSize := req.PageSize
  59. if page <= 0 {
  60. page = 1
  61. }
  62. if pageSize <= 0 {
  63. pageSize = 10
  64. } else if pageSize > 100 {
  65. pageSize = 100
  66. }
  67. offset := (page - 1) * pageSize
  68. result := query.Offset(offset).Limit(pageSize).Find(&res)
  69. if result.Error != nil {
  70. return nil, result.Error
  71. }
  72. return &v1.PaginatedResponse[adminApi.WafManageListRes]{
  73. Records: res,
  74. Page: page,
  75. PageSize: pageSize,
  76. Total: total,
  77. TotalPages: int(math.Ceil(float64(total) / float64(pageSize))),
  78. }, nil
  79. }