webforwarding.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. package waf
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. v1 "github.com/go-nunu/nunu-layout-advanced/api/v1"
  8. "github.com/go-nunu/nunu-layout-advanced/internal/model"
  9. "github.com/go-nunu/nunu-layout-advanced/internal/repository"
  10. "github.com/qiniu/qmgo"
  11. "go.mongodb.org/mongo-driver/bson"
  12. "go.mongodb.org/mongo-driver/bson/primitive"
  13. "go.mongodb.org/mongo-driver/mongo"
  14. "gorm.io/gorm"
  15. "time"
  16. )
  17. type WebForwardingRepository interface {
  18. GetWebForwarding(ctx context.Context, id int64) (*model.WebForwarding, error)
  19. AddWebForwarding(ctx context.Context, req *model.WebForwarding) (int, error)
  20. EditWebForwarding(ctx context.Context, req *model.WebForwarding) error
  21. DeleteWebForwarding(ctx context.Context, id int64) error
  22. GetWebForwardingPortCountByHostId(ctx context.Context, hostId int) (int64, error)
  23. GetWebForwardingDomainCountByHostId(ctx context.Context, hostId int) (int64, []string, error)
  24. GetWebForwardingWafWebAllIds(ctx context.Context, hostId int) ([]int, error)
  25. AddWebForwardingIps(ctx context.Context, req model.WebForwardingRule) (primitive.ObjectID, error)
  26. EditWebForwardingIps(ctx context.Context, req model.WebForwardingRule) error
  27. GetWebForwardingIpsByID(ctx context.Context, webId int) (*model.WebForwardingRule, error)
  28. DeleteWebForwardingIpsById(ctx context.Context, webId int) error
  29. // 获取域名数量
  30. GetDomainCount(ctx context.Context, hostId int, domain string) (int, error)
  31. // 获取IP数量等于1的IP
  32. GetIpCountByIp(ctx context.Context, ips []string) ([]v1.IpCountResult, error)
  33. GetSslCertId (ctx context.Context, sslPocyID int64) ([]v1.SslCertsJSON, error)
  34. // 获取CDN的web配置的id
  35. GetWebConfigId(ctx context.Context, id int64) (int64, error)
  36. // 获取域名
  37. GetDomainByHostIdPort(ctx context.Context, hostId int64, port string) ([]v1.Domain, error)
  38. // 获取CDN的web配置的id
  39. GetWebId(ctx context.Context, serverId int64) (int64, error)
  40. GetWebAll(ctx context.Context, hostIds []int) ([]int, error)
  41. }
  42. func NewWebForwardingRepository(
  43. repository *repository.Repository,
  44. ) WebForwardingRepository {
  45. return &webForwardingRepository{
  46. Repository: repository,
  47. }
  48. }
  49. type webForwardingRepository struct {
  50. *repository.Repository
  51. }
  52. func (r *webForwardingRepository) GetWebForwarding(ctx context.Context, id int64) (*model.WebForwarding, error) {
  53. var webForwarding model.WebForwarding
  54. if err := r.Db.WithContext(ctx).Where("id = ?", id).First(&webForwarding).Error; err != nil {
  55. return nil, err
  56. }
  57. return &webForwarding, nil
  58. }
  59. func (r *webForwardingRepository) AddWebForwarding(ctx context.Context, req *model.WebForwarding) (int, error) {
  60. if err := r.Db.WithContext(ctx).Create(req).Error; err != nil {
  61. return 0, err
  62. }
  63. return req.Id, nil
  64. }
  65. func (r *webForwardingRepository) EditWebForwarding(ctx context.Context, req *model.WebForwarding) error {
  66. forceUpdateFields := map[string]interface{}{
  67. "domain": req.Domain,
  68. "is_https": req.IsHttps,
  69. "proxy" : req.Proxy,
  70. "cc" : req.Cc,
  71. }
  72. // 核心逻辑:
  73. // 1. Model(req): 定位要更新的记录。
  74. // 2. Updates(req): 先用 struct 更新。GORM 会自动忽略 req 中的零值字段。
  75. // - 如果 req.Domain 是 "abc",它会被更新。
  76. // - 如果 req.Domain 是 "",它会被忽略。
  77. // - 如果 req.TargetURL 是 "xyz",它会被更新。
  78. // - 如果 req.TargetURL 是 "",它会被忽略。
  79. // 3. Updates(forceUpdateFields): 接着用 map 更新。这会无视零值,强制更新 map 中指定的字段。
  80. // - 它会用 req.Domain 的值(无论是 "abc" 还是 "")覆盖上一步的结果。
  81. //
  82. // 最终效果:
  83. // - Domain 字段总能被正确更新(无论新值是不是 "")。
  84. // - 其他字段遵循 GORM 的默认行为(非零值才更新)。
  85. // - 这一切都在一个 UPDATE 语句中完成。
  86. db := r.Db.WithContext(ctx).Model(req).Updates(req).Updates(forceUpdateFields)
  87. if db.Error != nil {
  88. return db.Error
  89. }
  90. return nil
  91. }
  92. func (r *webForwardingRepository) DeleteWebForwarding(ctx context.Context, id int64) error {
  93. if err := r.Db.WithContext(ctx).Where("id = ?", id).Delete(&model.WebForwarding{}).Error; err != nil {
  94. return err
  95. }
  96. return nil
  97. }
  98. func (r *webForwardingRepository) GetWebForwardingPortCountByHostId(ctx context.Context, hostId int) (int64, error) {
  99. var count int64
  100. if err := r.Db.Model(&model.WebForwarding{}).WithContext(ctx).Where("host_id = ?", hostId).Count(&count).Error; err != nil {
  101. return 0, err
  102. }
  103. return count, nil
  104. }
  105. func (r *webForwardingRepository) GetWebForwardingDomainCountByHostId(ctx context.Context, hostId int) (int64, []string, error) {
  106. var distinctDomains []string
  107. err := r.Db.Model(&model.WebForwarding{}).WithContext(ctx).
  108. Distinct(). // 确保我们只获取唯一的 domain 值
  109. Where("host_id = ? AND domain IS NOT NULL AND domain != ''", hostId). // 额外添加 domain != '' 以排除空字符串
  110. Pluck("domain", &distinctDomains).Error
  111. if err != nil {
  112. return 0, nil, err
  113. }
  114. count := int64(len(distinctDomains))
  115. return count, distinctDomains, nil
  116. }
  117. func (r *webForwardingRepository) GetWebForwardingWafWebAllIds(ctx context.Context, hostId int) ([]int, error) {
  118. var ids []int
  119. if err := r.Db.Model(&model.WebForwarding{}).WithContext(ctx).Where("host_id = ?", hostId).Select("id").Find(&ids).Error; err != nil {
  120. return nil, err
  121. }
  122. return ids, nil
  123. }
  124. // mongodb 插入
  125. func (r *webForwardingRepository) AddWebForwardingIps(ctx context.Context, req model.WebForwardingRule) (primitive.ObjectID, error) {
  126. collection := r.MongoDB.Collection("web_forwarding_rules")
  127. req.CreatedAt = time.Now()
  128. result, err := collection.InsertOne(ctx, req)
  129. if err != nil {
  130. return primitive.NilObjectID, fmt.Errorf("插入MongoDB失败: %w", err)
  131. }
  132. // 返回插入文档的ID
  133. return result.InsertedID.(primitive.ObjectID), nil
  134. }
  135. func (r *webForwardingRepository) EditWebForwardingIps(ctx context.Context, req model.WebForwardingRule) error {
  136. collection := r.MongoDB.Collection("web_forwarding_rules")
  137. updateData := bson.M{}
  138. if req.Uid != 0 {
  139. updateData["uid"] = req.Uid
  140. }
  141. if req.HostId != 0 {
  142. updateData["host_id"] = req.HostId
  143. }
  144. if req.WebId != 0 {
  145. updateData["web_id"] = req.WebId
  146. }
  147. if len(req.BackendList) > 0 {
  148. updateData["backend_list"] = req.BackendList
  149. }
  150. updateData["cdn_origin_ids"] = req.CdnOriginIds
  151. // 始终更新更新时间
  152. updateData["updated_at"] = time.Now()
  153. // 如果没有任何字段需要更新,则直接返回
  154. if len(updateData) == 0 {
  155. return nil
  156. }
  157. // 执行更新
  158. update := bson.M{"$set": updateData}
  159. err := collection.UpdateOne(ctx, bson.M{"web_id": req.WebId}, update)
  160. if err != nil {
  161. return fmt.Errorf("更新MongoDB文档失败: %w", err)
  162. }
  163. return nil
  164. }
  165. func (r *webForwardingRepository) GetWebForwardingIpsByID(ctx context.Context, webId int) (*model.WebForwardingRule, error) {
  166. // 获取集合
  167. collection := r.MongoDB.Collection("web_forwarding_rules")
  168. // 创建一个结构体来存储查询到的文档
  169. var rule model.WebForwardingRule
  170. // 使用 FindByID 方法来查找文档
  171. // FindByID 是 QMgo 封装的一个方便的方法,它内部会构建查询 _id = id
  172. err := collection.Find(ctx, qmgo.M{"web_id": webId}).One(&rule) // QMgo 的 FindOne 返回一个 QueryBuilder,接着调用 .One() 来执行查询并解码到 rule
  173. if err != nil {
  174. if errors.Is(err, mongo.ErrNoDocuments) {
  175. return nil, nil
  176. }
  177. // 其他错误
  178. return nil, fmt.Errorf("查询MongoDB失败: %w", err)
  179. }
  180. // 返回找到的文档
  181. return &rule, nil
  182. }
  183. func (r *webForwardingRepository) DeleteWebForwardingIpsById(ctx context.Context, webId int) error {
  184. collection := r.MongoDB.Collection("web_forwarding_rules")
  185. err := collection.Remove(ctx, bson.M{"web_id": webId})
  186. if err != nil {
  187. if errors.Is(err, mongo.ErrNoDocuments) {
  188. return fmt.Errorf("记录不存在")
  189. }
  190. return fmt.Errorf("删除MongoDB文档失败: %w", err)
  191. }
  192. return nil
  193. }
  194. // 获取域名数量
  195. func (r *webForwardingRepository) GetDomainCount(ctx context.Context, hostId int, domain string) (int, error) {
  196. var count int64
  197. if err := r.Db.Model(&model.WebForwarding{}).WithContext(ctx).Where("host_id = ? AND domain = ?", hostId, domain).Count(&count).Error; err != nil {
  198. return 0, err
  199. }
  200. return int(count), nil
  201. }
  202. // 获取IP数量等于1的IP
  203. func (r *webForwardingRepository) GetIpCountByIp(ctx context.Context, ips []string) ([]v1.IpCountResult, error) {
  204. if len(ips) == 0 {
  205. return []v1.IpCountResult{}, nil
  206. }
  207. pipeline := []bson.M{
  208. // 第 1 步: $unwind - 展开 backend_list 数组
  209. // 将包含多个 backend 对象的文档拆分成多条,每条只包含一个 backend 对象。
  210. {
  211. "$unwind": "$backend_list",
  212. },
  213. // 第 2 步: $addFields - 添加一个新字段用于存放解析出的 IP
  214. // 我们需要从 "ip:port" 格式的 addr 字段中把 ip 提取出来。
  215. // 使用 $split 操作符按 ":" 分割字符串,然后用 $arrayElemAt 取第一个元素。
  216. {
  217. "$addFields": bson.M{
  218. "extracted_ip": bson.M{
  219. "$arrayElemAt": []interface{}{
  220. bson.M{"$split": []string{"$backend_list.addr", ":"}},
  221. 0,
  222. },
  223. },
  224. },
  225. },
  226. // 第 3 步: $match - 匹配我们关心的 IP
  227. // 在上一步创建的 extracted_ip 字段上进行匹配。
  228. {
  229. "$match": bson.M{
  230. "extracted_ip": bson.M{"$in": ips},
  231. },
  232. },
  233. // 第 4 步: $group - 按解析出的 IP 地址进行分组和计数
  234. {
  235. "$group": bson.M{
  236. "_id": "$extracted_ip", // 使用我们新创建的 extracted_ip 字段作为分组依据
  237. "count": bson.M{"$sum": 1},
  238. },
  239. },
  240. // 第 5 步: $project - 格式化最终输出
  241. // 这个阶段和之前一样,只是为了让输出结果更清晰,并匹配 Go 结构体。
  242. {
  243. "$project": bson.M{
  244. "_id": 0,
  245. "ip": "$_id",
  246. "count": 1,
  247. },
  248. },
  249. }
  250. var results []v1.IpCountResult
  251. // 使用 qmgo 执行聚合查询
  252. err := r.MongoDB.Collection("web_forwarding_rules").Aggregate(ctx, pipeline).All(&results)
  253. if err != nil {
  254. // 加上错误包装,方便调试
  255. return nil, fmt.Errorf("聚合查询 web_forwarding_rules 失败: %w", err)
  256. }
  257. return results, nil
  258. }
  259. func (r *webForwardingRepository) GetSslCertId (ctx context.Context, sslPolicyID int64) ([]v1.SslCertsJSON, error) {
  260. var certsJSON string
  261. // 2. 查询数据库,只获取 `certs` 字段的字符串内容
  262. // 使用 Scopes 来确保没有不必要的 ORDER BY 子句,或者直接用 Raw/Scan
  263. // 但在这里,用 .First(&certsJSON) 通常是安全的,因为目标是简单类型 string
  264. err := r.DBWithName(ctx, "cdn").WithContext(ctx).
  265. Table("cloud_ssl_policies").
  266. Select("certs").
  267. Where("id = ?", sslPolicyID).
  268. Row(). // 获取 sql.Row
  269. Scan(&certsJSON) // 将结果扫描到字符串变量中
  270. // 如果查询出错,或者没有找到记录 (sql.ErrNoRows)
  271. if err != nil {
  272. if err == gorm.ErrRecordNotFound {
  273. // 如果记录不存在是正常情况,可以返回一个空切片和nil错误
  274. return []v1.SslCertsJSON{}, nil
  275. }
  276. return nil, err
  277. }
  278. // 如果certs字段在数据库中可能是NULL或者空字符串,需要处理
  279. if certsJSON == "" {
  280. return []v1.SslCertsJSON{}, nil
  281. }
  282. // 3. 将JSON字符串反序列化到Go结构体切片中
  283. var res []v1.SslCertsJSON
  284. err = json.Unmarshal([]byte(certsJSON), &res)
  285. if err != nil {
  286. // 这里是真正的JSON格式转换错误
  287. return nil, err
  288. }
  289. return res, nil
  290. }
  291. // 获取CDN的web配置的id
  292. func (r *webForwardingRepository) GetWebConfigId(ctx context.Context, id int64) (int64, error) {
  293. var webConfigId int64
  294. if err := r.DBWithName(ctx,"cdn").Table("cloud_servers").Where("id = ?", id).Select("webId").Scan(&webConfigId).Error; err != nil {
  295. return 0, err
  296. }
  297. return webConfigId, nil
  298. }
  299. func (r *webForwardingRepository) GetDomainByHostIdPort(ctx context.Context, hostId int64, port string) ([]v1.Domain, error) {
  300. var domains []v1.Domain
  301. if err := r.Db.WithContext(ctx).Model(&model.WebForwarding{}).Where("host_id = ? AND port = ?", hostId, port).Select("domain,id,is_https").Scan(&domains).Error; err != nil {
  302. return nil, err
  303. }
  304. return domains, nil
  305. }
  306. // 获取CDN的web配置的id
  307. func (r *webForwardingRepository) GetWebId(ctx context.Context, serverId int64) (int64, error) {
  308. var webId int64
  309. if err := r.DBWithName(ctx,"cdn").Table("cloud_servers").Where("id = ?", serverId).Select("webId").Scan(&webId).Error; err != nil {
  310. return 0, err
  311. }
  312. return webId, nil
  313. }
  314. func (r *webForwardingRepository) GetWebAll(ctx context.Context, hostIds []int) ([]int, error) {
  315. var res []int
  316. if err := r.Db.Model(&model.WebForwarding{}).WithContext(ctx).Where("host_id IN ?", hostIds).Select("cdn_web_id").Scan(&res).Error; err != nil {
  317. return nil, err
  318. }
  319. return res, nil
  320. }