ZoneCloudflareServer.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881
  1. package server
  2. import (
  3. "bytes"
  4. "cfTest/cloudflareApi/zone"
  5. "context"
  6. "encoding/json"
  7. "errors"
  8. "fmt"
  9. "github.com/cloudflare/cloudflare-go"
  10. "github.com/samber/lo"
  11. "io"
  12. "io/ioutil"
  13. "log"
  14. "net/http"
  15. "strings"
  16. "time"
  17. )
  18. type ZoneServer struct {
  19. zone.UnimplementedZoneCloudflareServer
  20. }
  21. type Subscription struct {
  22. ID string `json:"id"`
  23. RatePlan struct {
  24. ID string `json:"id"`
  25. PublicName string `json:"public_name"`
  26. Currency string `json:"currency"`
  27. Scope string `json:"scope"`
  28. ExternallyManaged bool `json:"externally_managed"`
  29. Sets []string `json:"sets"`
  30. IsContract bool `json:"is_contract"`
  31. } `json:"rate_plan"`
  32. ComponentValues []struct {
  33. Name string `json:"name"`
  34. Value int `json:"value"`
  35. Default int `json:"default,omitempty"`
  36. } `json:"component_values"`
  37. Zone struct {
  38. ID string `json:"id"`
  39. Name string `json:"name"`
  40. } `json:"zone"`
  41. Frequency string `json:"frequency"`
  42. Currency string `json:"currency"`
  43. Price int `json:"price"`
  44. Product struct {
  45. Name string `json:"name"`
  46. Period string `json:"period"`
  47. Billing string `json:"billing"`
  48. PublicName string `json:"public_name"`
  49. Duration int `json:"duration"`
  50. } `json:"product"`
  51. CancelAtPeriodEnd bool `json:"cancel_at_period_end"`
  52. CreatedDate time.Time `json:"created_date"`
  53. }
  54. var ArgoSubscriptionId = "argo_zone_ent_tryout"
  55. func (s *ZoneServer) GetArgoSettingSubscription(ctx context.Context, request *zone.IdRequest) (*zone.ArgoSetting, error) {
  56. //设置HTTP请求
  57. client := &http.Client{}
  58. req, err := http.NewRequest("GET", "https://api.cloudflare.com/client/v4/zones/"+request.ZoneId+"/subscriptions", nil)
  59. if err != nil {
  60. return nil, err
  61. }
  62. req.Header.Add("X-Auth-Key", request.GetApiKey())
  63. req.Header.Add("X-Auth-Email", request.GetApiEmail())
  64. //执行HTTP请求
  65. resp, err := client.Do(req)
  66. if err != nil {
  67. return nil, err
  68. }
  69. defer func(Body io.ReadCloser) {
  70. _ = Body.Close()
  71. }(resp.Body)
  72. body, _ := ioutil.ReadAll(resp.Body)
  73. type ResponseType struct {
  74. Errors []interface{} `json:"errors"`
  75. Messages []interface{} `json:"messages"`
  76. Result []Subscription `json:"result"`
  77. ResultInfo struct {
  78. NextPage bool `json:"next_page"`
  79. } `json:"result_info"`
  80. Success bool `json:"success"`
  81. }
  82. var r ResponseType
  83. err = json.Unmarshal(body, &r)
  84. //处理返回逻辑
  85. if err != nil {
  86. return nil, fmt.Errorf("%s: %w", "error unmarshalling the JSON response", err)
  87. }
  88. if r.Success != true {
  89. return nil, fmt.Errorf("%s", r.Errors)
  90. }
  91. log.Printf("Response: %v", r)
  92. for _, v := range r.Result {
  93. if v.RatePlan.ID == ArgoSubscriptionId {
  94. return &zone.ArgoSetting{Enabled: true}, nil
  95. }
  96. }
  97. return &zone.ArgoSetting{Enabled: false}, nil
  98. }
  99. func (s *ZoneServer) CreateArgoSettingSubscription(ctx context.Context, request *zone.IdRequest) (*zone.ArgoSetting, error) {
  100. type RequestType struct {
  101. RatePlan struct {
  102. ID string `json:"id"`
  103. } `json:"rate_plan"`
  104. Zone struct {
  105. ID string `json:"id"`
  106. Name string `json:"name"`
  107. } `json:"zone"`
  108. }
  109. type ResponseType struct {
  110. Errors []interface{} `json:"errors"`
  111. Messages []interface{} `json:"messages"`
  112. Result Subscription `json:"result"`
  113. Success bool `json:"success"`
  114. }
  115. bytesData, err := json.Marshal(RequestType{
  116. RatePlan: struct {
  117. ID string `json:"id"`
  118. }{
  119. ID: ArgoSubscriptionId,
  120. },
  121. Zone: struct {
  122. ID string `json:"id"`
  123. Name string `json:"name"`
  124. }{
  125. ID: request.ZoneId,
  126. },
  127. })
  128. if err != nil {
  129. return nil, err
  130. }
  131. //设置HTTP请求
  132. client := &http.Client{}
  133. req, err := http.NewRequest("POST", "https://api.cloudflare.com/client/v4/zones/"+request.ZoneId+"/subscription", bytes.NewReader(bytesData))
  134. if err != nil {
  135. return nil, err
  136. }
  137. req.Header.Add("X-Auth-Key", request.GetApiKey())
  138. req.Header.Add("X-Auth-Email", request.GetApiEmail())
  139. //执行HTTP请求
  140. resp, err := client.Do(req)
  141. if err != nil {
  142. return nil, err
  143. }
  144. defer func(Body io.ReadCloser) {
  145. _ = Body.Close()
  146. }(resp.Body)
  147. body, _ := ioutil.ReadAll(resp.Body)
  148. var r ResponseType
  149. err = json.Unmarshal(body, &r)
  150. //处理返回逻辑
  151. if err != nil {
  152. return nil, fmt.Errorf("%s: %w", "error unmarshalling the JSON response", err)
  153. }
  154. if r.Success != true {
  155. return nil, fmt.Errorf("%s", r.Errors)
  156. }
  157. log.Printf("Response: %v", r)
  158. if r.Result.RatePlan.ID == ArgoSubscriptionId {
  159. return &zone.ArgoSetting{Enabled: true}, nil
  160. }
  161. return &zone.ArgoSetting{Enabled: false}, nil
  162. }
  163. func (s *ZoneServer) UpdateArgoSetting(ctx context.Context, requestCloudflare *zone.UpdateArgoRequestCloudflare) (*zone.ArgoSetting, error) {
  164. api, err := cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  165. if err != nil {
  166. return nil, err
  167. }
  168. settingValue := Proto2GoArgoSetting(requestCloudflare.GetArgoSetting())
  169. setting, err := api.UpdateArgoSmartRouting(ctx, requestCloudflare.ZoneId, settingValue)
  170. if err != nil {
  171. return nil, err
  172. }
  173. return Go2ProtoArgoSetting(setting.Value), nil
  174. }
  175. func (s *ZoneServer) GetArgoSetting(ctx context.Context, requestCloudflare *zone.IdRequest) (*zone.ArgoSetting, error) {
  176. api, err := cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  177. if err != nil {
  178. return nil, err
  179. }
  180. setting, err := api.ArgoSmartRouting(ctx, requestCloudflare.ZoneId)
  181. if err != nil {
  182. return nil, err
  183. }
  184. return Go2ProtoArgoSetting(setting.Value), nil
  185. }
  186. func (s *ZoneServer) ZoneIDByNameCloudflare(ctx context.Context, requestCloudflare *zone.ZoneIDByNameRequestCloudflare) (*zone.ZoneIDByNameReplyCloudflare, error) {
  187. api, err := cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  188. if err != nil {
  189. return nil, err
  190. }
  191. id, err := api.ZoneIDByName(requestCloudflare.ZoneName)
  192. if err != nil {
  193. return nil, err
  194. }
  195. return &zone.ZoneIDByNameReplyCloudflare{ZoneId: id}, err
  196. }
  197. func (s *ZoneServer) ZoneDetails(ctx context.Context, requestCloudflare *zone.ZoneDetailsRequestCloudflare) (*zone.ZoneDetailsReplyCloudflare, error) {
  198. api, err := cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  199. if err != nil {
  200. return nil, err
  201. }
  202. ctxAPI := context.Background()
  203. details, err := api.ZoneDetails(ctxAPI, requestCloudflare.GetZoneId())
  204. if err != nil {
  205. return nil, err
  206. }
  207. return &zone.ZoneDetailsReplyCloudflare{
  208. Result: Go2ProtoZone(details),
  209. }, err
  210. }
  211. func (s *ZoneServer) GetZones(ctx context.Context, requestCloudflare *zone.GetZonesRequestCloudflare) (*zone.GetZonesReplyCloudflare, error) {
  212. api, err := cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  213. if err != nil {
  214. return nil, err
  215. }
  216. details, err := api.ListZones(ctx, "name", requestCloudflare.GetDomain())
  217. if err != nil {
  218. return nil, err
  219. }
  220. list := make([]*zone.ZoneCloudflareEntity, len(details))
  221. for i, detail := range details {
  222. list[i] = Go2ProtoZone(detail)
  223. }
  224. return &zone.GetZonesReplyCloudflare{
  225. Result: list,
  226. Success: true,
  227. }, err
  228. }
  229. func (s *ZoneServer) ListZones(ctx context.Context, requestCloudflare *zone.ListZonesRequestCloudflare) (*zone.ZonesList, error) {
  230. api, err := cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  231. if err != nil {
  232. return nil, err
  233. }
  234. ctxAPI := context.Background()
  235. details, err := api.ListZones(ctxAPI)
  236. if err != nil {
  237. return nil, err
  238. }
  239. list := make([]*zone.ZoneCloudflareEntity, len(details))
  240. for i, detail := range details {
  241. list[i] = Go2ProtoZone(detail)
  242. }
  243. return &zone.ZonesList{
  244. Result: list,
  245. }, err
  246. }
  247. func (s *ZoneServer) ListZonesByAccountId(ctx context.Context, requestCloudflare *zone.ListZonesByAccountIdRequestCloudflare) (*zone.ZonesList, error) {
  248. api, err := cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  249. if err != nil {
  250. return nil, err
  251. }
  252. ctxAPI := context.Background()
  253. opt := cloudflare.WithZoneFilters("", requestCloudflare.AccountId, "")
  254. details, err := api.ListZonesContext(ctxAPI, opt)
  255. if err != nil {
  256. return nil, err
  257. }
  258. list := make([]*zone.ZoneCloudflareEntity, len(details.Result))
  259. for i, detail := range details.Result {
  260. list[i] = Go2ProtoZone(detail)
  261. }
  262. return &zone.ZonesList{
  263. Result: list,
  264. }, err
  265. }
  266. func (s *ZoneServer) EditZone(ctx context.Context, requestCloudflare *zone.EditZoneRequestCloudflare) (*zone.EditZoneReplyCloudflare, error) {
  267. api, err := cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  268. if err != nil {
  269. return nil, err
  270. }
  271. ctxAPI := context.Background()
  272. opts := cloudflare.ZoneOptions{}
  273. opts.Paused = requestCloudflare.Paused
  274. if requestCloudflare.PlanId != nil {
  275. opts.Plan = &cloudflare.ZonePlan{
  276. ZonePlanCommon: cloudflare.ZonePlanCommon{
  277. ID: requestCloudflare.GetPlanId(),
  278. },
  279. }
  280. }
  281. if requestCloudflare.Type != nil {
  282. opts.Type = requestCloudflare.GetType()
  283. }
  284. editZone, err := api.EditZone(ctxAPI, requestCloudflare.GetZoneId(), opts)
  285. if err != nil {
  286. return nil, err
  287. }
  288. return &zone.EditZoneReplyCloudflare{
  289. Result: Go2ProtoZone(editZone),
  290. Success: true,
  291. }, nil
  292. }
  293. func (s *ZoneServer) DeleteZone(ctx context.Context, requestCloudflare *zone.DeleteZoneRequestCloudflare) (*zone.DeleteZoneReplyCloudflare, error) {
  294. api, err := cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  295. if err != nil {
  296. return nil, err
  297. }
  298. ctxAPI := context.Background()
  299. deleteZone, err := api.DeleteZone(ctxAPI, requestCloudflare.GetZoneId())
  300. if err != nil {
  301. return nil, err
  302. }
  303. return &zone.DeleteZoneReplyCloudflare{
  304. Success: true,
  305. Id: deleteZone.ID,
  306. }, nil
  307. }
  308. func (s *ZoneServer) CreateZone(ctx context.Context, requestCloudflare *zone.CreateZoneRequestCloudflare) (*zone.CreateZoneReplyCloudflare, error) {
  309. api, err := cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  310. if err != nil {
  311. return nil, err
  312. }
  313. ctxAPI := context.Background()
  314. account, _, err := api.Account(ctxAPI, requestCloudflare.GetAccountId())
  315. if err != nil {
  316. return nil, err
  317. }
  318. createZone, err := api.CreateZone(ctxAPI, requestCloudflare.GetDomain(), false, account, "partial")
  319. if err != nil {
  320. return nil, err
  321. }
  322. return &zone.CreateZoneReplyCloudflare{
  323. Success: true,
  324. Id: createZone.ID,
  325. }, nil
  326. }
  327. func (s *ZoneServer) SetZonePlan(ctx context.Context, requestCloudflare *zone.SetZonePlanRequestCloudflare) (*zone.SetZonePlanReplyCloudflare, error) {
  328. api, err := cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  329. if err != nil {
  330. return nil, err
  331. }
  332. ctxAPI := context.Background()
  333. err = api.ZoneSetPlan(ctxAPI, requestCloudflare.GetZoneId(), requestCloudflare.GetZonePlan())
  334. if err != nil {
  335. return nil, err
  336. }
  337. return &zone.SetZonePlanReplyCloudflare{
  338. Success: true,
  339. }, nil
  340. }
  341. func (s *ZoneServer) ActivationCheck(ctx context.Context, requestCloudflare *zone.ActivationCheckRequestCloudflare) (*zone.ActivationCheckReplyCloudflare, error) {
  342. api, err := cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  343. if err != nil {
  344. return nil, err
  345. }
  346. ctxAPI := context.Background()
  347. activationCheck, err := api.ZoneActivationCheck(ctxAPI, requestCloudflare.GetZoneId())
  348. if err != nil {
  349. return nil, err
  350. }
  351. return &zone.ActivationCheckReplyCloudflare{
  352. Success: activationCheck.Success,
  353. }, nil
  354. }
  355. var phaseMap = map[zone.Phase]string{
  356. zone.Phase_http_request_sanitize: "http_request_sanitize",
  357. zone.Phase_http_request_transform: "http_request_transform",
  358. zone.Phase_http_request_origin: "http_request_origin",
  359. zone.Phase_http_request_cache_settings: "http_request_cache_settings",
  360. zone.Phase_http_config_settings: "http_config_settings",
  361. //zone.Phase_http_request_dynamic_redirect: "http_request_dynamic_redirect",
  362. //zone.Phase_ddos_l7: "ddos_l7",
  363. //zone.Phase_http_request_firewall_custom: "http_request_firewall_custom",
  364. //zone.Phase_http_ratelimit: "http_ratelimit",
  365. //zone.Phase_http_request_firewall_managed: "http_request_firewall_managed",
  366. //zone.Phase_http_request_sbfm: "http_request_sbfm",
  367. //zone.Phase_http_request_redirect: "http_request_redirect",
  368. zone.Phase_http_request_late_transform: "http_request_late_transform",
  369. //zone.Phase_http_custom_errors: "http_custom_errors",
  370. zone.Phase_http_response_headers_transform: "http_response_headers_transform",
  371. //zone.Phase_http_response_firewall_managed: "http_response_firewall_managed",
  372. //zone.Phase_http_log_custom_fields: "http_log_custom_fields",
  373. }
  374. func (s *ZoneServer) ListZoneRuleSets(ctx context.Context, requestCloudflare *zone.ListZoneRuleSetsRequestCloudflare) (*zone.RuleSetList, error) {
  375. api, err := cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  376. if err != nil {
  377. return nil, err
  378. }
  379. ctxAPI := context.Background()
  380. zoneIdentifier := cloudflare.ZoneIdentifier(requestCloudflare.GetZoneId())
  381. ListRulesetsParams := cloudflare.ListRulesetsParams{}
  382. goRuleSets, err := api.ListRulesets(ctxAPI, zoneIdentifier, ListRulesetsParams)
  383. if err != nil {
  384. return nil, err
  385. }
  386. filterMap := lo.FilterMap[cloudflare.Ruleset, *zone.RuleSet](goRuleSets, func(goRuleSet cloudflare.Ruleset, _ int) (*zone.RuleSet, bool) {
  387. protoRuleSet := Go2ProtoRuleSet(&goRuleSet)
  388. return protoRuleSet, true
  389. })
  390. return &zone.RuleSetList{RuleSets: filterMap}, nil
  391. }
  392. func (s *ZoneServer) CreateZoneRuleSet(ctx context.Context, requestCloudflare *zone.CreateZoneRuleSetRequestCloudflare) (*zone.CreateZoneRuleSetReplyCloudflare, error) {
  393. api, err := cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  394. if err != nil {
  395. return nil, err
  396. }
  397. ctxAPI := context.Background()
  398. filterMap := lo.FilterMap[*zone.Rule, cloudflare.RulesetRule](requestCloudflare.Rules, func(rule *zone.Rule, index int) (cloudflare.RulesetRule, bool) {
  399. ruleResult, err := Proto2GoRulesetRuleByPhase(rule, requestCloudflare.RuleSet.Phase)
  400. if err != nil || ruleResult == nil {
  401. return cloudflare.RulesetRule{}, false
  402. }
  403. return *ruleResult, true
  404. })
  405. zoneIdentifier := cloudflare.ZoneIdentifier(requestCloudflare.GetZoneId())
  406. createRulesetParams := cloudflare.CreateRulesetParams{
  407. Name: requestCloudflare.RuleSet.Name,
  408. Kind: requestCloudflare.RuleSet.Kind,
  409. Phase: phaseMap[requestCloudflare.RuleSet.Phase],
  410. Rules: filterMap,
  411. }
  412. _, err = api.CreateRuleset(ctxAPI, zoneIdentifier, createRulesetParams)
  413. if err != nil {
  414. return &zone.CreateZoneRuleSetReplyCloudflare{Success: false}, err
  415. }
  416. //protoRuleSet := Go2ProtoRuleSet(&goRuleSet)
  417. return &zone.CreateZoneRuleSetReplyCloudflare{Success: true}, nil
  418. }
  419. func (s *ZoneServer) DeleteZoneRuleSet(ctx context.Context, requestCloudflare *zone.DeleteZoneRuleSetRequestCloudflare) (*zone.DeleteZoneRuleSetReplyCloudflare, error) {
  420. api, err := cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  421. if err != nil {
  422. return nil, err
  423. }
  424. ctxAPI := context.Background()
  425. zoneIdentifier := cloudflare.ZoneIdentifier(requestCloudflare.GetZoneId())
  426. err = api.DeleteRuleset(ctxAPI, zoneIdentifier, requestCloudflare.GetRuleSetId())
  427. if err != nil {
  428. return &zone.DeleteZoneRuleSetReplyCloudflare{Success: false}, err
  429. }
  430. return &zone.DeleteZoneRuleSetReplyCloudflare{Success: true}, nil
  431. }
  432. func (s *ZoneServer) UpdateRuleSetByRuleSetId(ctx context.Context, requestCloudflare *zone.UpdateRuleSetByRuleSetIdRequestCloudflare) (*zone.RuleSet, error) {
  433. api, err := cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  434. if err != nil {
  435. return nil, err
  436. }
  437. ctxAPI := context.Background()
  438. filterMap := lo.FilterMap[*zone.Rule, cloudflare.RulesetRule](requestCloudflare.Rules, func(rule *zone.Rule, index int) (cloudflare.RulesetRule, bool) {
  439. ruleResult, err := Proto2GoRulesetRuleByPhase(rule, requestCloudflare.Phase)
  440. if err != nil || ruleResult == nil {
  441. return cloudflare.RulesetRule{}, false
  442. }
  443. return *ruleResult, true
  444. })
  445. zoneIdentifier := cloudflare.ZoneIdentifier(requestCloudflare.GetZoneId())
  446. updateRulesetParams := cloudflare.UpdateRulesetParams{
  447. ID: requestCloudflare.RuleSetId,
  448. Rules: filterMap,
  449. }
  450. goRuleSet, err := api.UpdateRuleset(ctxAPI, zoneIdentifier, updateRulesetParams)
  451. if err != nil {
  452. return nil, err
  453. }
  454. protoRuleSet := Go2ProtoRuleSet(&goRuleSet)
  455. return protoRuleSet, nil
  456. }
  457. func (s *ZoneServer) GetRuleSet(ctx context.Context, requestCloudflare *zone.GetRuleSetRequestCloudflare) (*zone.RuleList, error) {
  458. api, err := cloudflare.New(requestCloudflare.ApiKey, requestCloudflare.ApiEmail)
  459. if err != nil {
  460. return nil, err
  461. }
  462. ctxAPI := context.Background()
  463. switch phaseMap[requestCloudflare.Phase] {
  464. case "http_request_transform", "http_request_late_transform", "http_response_headers_transform":
  465. default:
  466. return nil, errors.New("未定义规则阶段")
  467. }
  468. zoneIdentifier := cloudflare.ZoneIdentifier(requestCloudflare.GetZoneId())
  469. ruleset, err := api.GetEntrypointRuleset(ctxAPI, zoneIdentifier, phaseMap[requestCloudflare.Phase])
  470. if err != nil {
  471. _, ok := err.(*cloudflare.NotFoundError)
  472. if ok {
  473. ruleset.Rules = make([]cloudflare.RulesetRule, 0)
  474. err = nil
  475. } else {
  476. return nil, err
  477. }
  478. }
  479. filterMap := lo.FilterMap[cloudflare.RulesetRule, *zone.Rule](ruleset.Rules, func(rule cloudflare.RulesetRule, _ int) (*zone.Rule, bool) {
  480. phase, err := Go2ProtoRuleRuleByPhase(&rule, ruleset.Phase)
  481. if err != nil {
  482. return nil, false
  483. }
  484. return phase, true
  485. })
  486. return &zone.RuleList{Rules: filterMap}, nil
  487. }
  488. func (s *ZoneServer) UpdateRuleSet(ctx context.Context, requestCloudflare *zone.UpdateRuleSetRequestCloudflare) (*zone.RuleList, error) {
  489. api, err := cloudflare.New(requestCloudflare.ApiKey, requestCloudflare.ApiEmail)
  490. if err != nil {
  491. return nil, err
  492. }
  493. ctxAPI := context.Background()
  494. phase := phaseMap[requestCloudflare.Phase]
  495. filterMap := lo.FilterMap[*zone.Rule, cloudflare.RulesetRule](requestCloudflare.Rules, func(rule *zone.Rule, index int) (cloudflare.RulesetRule, bool) {
  496. ruleResult, err := Proto2GoRulesetRuleByPhase(rule, requestCloudflare.Phase)
  497. if err != nil || ruleResult == nil {
  498. return cloudflare.RulesetRule{}, false
  499. }
  500. return *ruleResult, true
  501. })
  502. //for _, rule := range requestCloudflare.Rules {
  503. // ruleResult, err := Proto2GoRulesetRuleByPhase(rule, requestCloudflare.Phase)
  504. // if err != nil {
  505. // return nil, err
  506. // }
  507. // if ruleResult != nil {
  508. // ruleSet.Rules = append(ruleSet.Rules, *ruleResult)
  509. // }
  510. //}
  511. zoneIdentifier := cloudflare.ZoneIdentifier(requestCloudflare.GetZoneId())
  512. updateEntrypointRulesetParams := cloudflare.UpdateEntrypointRulesetParams{
  513. Phase: phase,
  514. Rules: filterMap,
  515. }
  516. ruleset, err := api.UpdateEntrypointRuleset(ctxAPI, zoneIdentifier, updateEntrypointRulesetParams)
  517. if err != nil {
  518. return nil, err
  519. }
  520. rulesReturn := lo.FilterMap[cloudflare.RulesetRule, *zone.Rule](ruleset.Rules, func(rule cloudflare.RulesetRule, _ int) (*zone.Rule, bool) {
  521. ruleReturn, err := Go2ProtoRuleRuleByPhase(&rule, ruleset.Phase)
  522. if err != nil {
  523. return nil, false
  524. }
  525. return ruleReturn, true
  526. })
  527. //var rulesReturn []*zone.Rule
  528. //for _, rule := range rulesetResult.Rules {
  529. // ruleReturn, err := Go2ProtoRuleRuleByPhase(&rule, rulesetResult.Phase)
  530. // if err != nil {
  531. // return nil, err
  532. // }
  533. // if ruleReturn != nil {
  534. // rulesReturn = append(rulesReturn, ruleReturn)
  535. // }
  536. //}
  537. return &zone.RuleList{Rules: rulesReturn}, nil
  538. }
  539. //func UpdateRuleSet(apiKey, apiEmail, zoneID, rulesetPhase string, ruleset cloudflare.Ruleset) (*cloudflare.Ruleset, error) {
  540. // api, err := cloudflare.New(apiKey, apiEmail)
  541. // if err != nil {
  542. // return nil, err
  543. // }
  544. // ctxAPI := context.Background()
  545. // phase, err := api.UpdateZoneRulesetPhase(ctxAPI, zoneID, rulesetPhase, ruleset)
  546. // if err != nil {
  547. // return nil, err
  548. // }
  549. // return &phase, nil
  550. //}
  551. //PageRule CURD
  552. func (s *ZoneServer) ListPageRule(ctx context.Context, requestCloudflare *zone.ListPageRuleRequestCloudflare) (*zone.PageRuleList, error) {
  553. api, err := cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  554. if err != nil {
  555. return nil, err
  556. }
  557. ctxAPI := context.Background()
  558. rules, err := api.ListPageRules(ctxAPI, requestCloudflare.GetZoneId())
  559. if err != nil {
  560. return nil, err
  561. }
  562. filterMap := lo.FilterMap[cloudflare.PageRule, *zone.PageRule](rules, func(rule cloudflare.PageRule, _ int) (*zone.PageRule, bool) {
  563. pageRule := Go2ProtoPageRule(&rule)
  564. return pageRule, true
  565. })
  566. return &zone.PageRuleList{PageRules: filterMap}, nil
  567. }
  568. func (s *ZoneServer) CreatePageRule(ctx context.Context, requestCloudflare *zone.CreatePageRuleRequestCloudflare) (*zone.PageRule, error) {
  569. api, err := cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  570. if err != nil {
  571. return nil, err
  572. }
  573. ctxAPI := context.Background()
  574. rule, err := Proto2GoPageRule(requestCloudflare.PageRule)
  575. if err != nil {
  576. return nil, err
  577. }
  578. pageRule, err := api.CreatePageRule(ctxAPI, requestCloudflare.GetZoneId(), *rule)
  579. if err != nil {
  580. return nil, err
  581. }
  582. return Go2ProtoPageRule(pageRule), nil
  583. }
  584. func (s *ZoneServer) UpdatePageRule(ctx context.Context, requestCloudflare *zone.UpdatePageRuleRequestCloudflare) (*zone.PageRule, error) {
  585. api, err := cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  586. if err != nil {
  587. return nil, err
  588. }
  589. ctxAPI := context.Background()
  590. rule, err := Proto2GoPageRule(requestCloudflare.PageRule)
  591. if err != nil {
  592. return nil, err
  593. }
  594. err = api.UpdatePageRule(ctxAPI, requestCloudflare.GetZoneId(), rule.ID, *rule)
  595. if err != nil {
  596. return nil, err
  597. }
  598. return requestCloudflare.PageRule, nil
  599. }
  600. func (s *ZoneServer) DeletePageRule(ctx context.Context, requestCloudflare *zone.DeletePageRuleRequestCloudflare) (*zone.PageRule, error) {
  601. api, err := cloudflare.New(requestCloudflare.GetApiKey(), requestCloudflare.GetApiEmail())
  602. if err != nil {
  603. return nil, err
  604. }
  605. ctxAPI := context.Background()
  606. err = api.DeletePageRule(ctxAPI, requestCloudflare.ZoneId, requestCloudflare.PageRuleId)
  607. if err != nil {
  608. return nil, err
  609. }
  610. return &zone.PageRule{}, nil
  611. }
  612. //func UpdatePageRule(apiKey, apiEmail, zoneID string, rule *zone.PageRule) (*zone.PageRule, error) {
  613. // api, err := cloudflare.New(apiKey, apiEmail)
  614. // if err != nil {
  615. // return nil, err
  616. // }
  617. //
  618. // ctxAPI := context.Background()
  619. // goPageRule, err := Proto2GoPageRule(rule)
  620. // if err != nil {
  621. // return nil, err
  622. // }
  623. // pageRule, err := api.CreatePageRule(ctxAPI, zoneID, *goPageRule)
  624. // if err != nil {
  625. // return nil, err
  626. // }
  627. //
  628. // protoPageRule := Go2ProtoPageRule(pageRule)
  629. //
  630. // return protoPageRule, nil
  631. //}
  632. type PageRuleActionCacheKeyFieldsQueryString struct {
  633. Exclude interface{} `json:"exclude"`
  634. Include interface{} `json:"include"`
  635. }
  636. type PageRuleActionCacheKeyFields struct {
  637. QueryString PageRuleActionCacheKeyFieldsQueryString `json:"query_string"`
  638. }
  639. type UpdatePageRulesPrioritiesStruct struct {
  640. Id string `json:"id"`
  641. Priority int `json:"priority"`
  642. }
  643. func (s *ZoneServer) UpdatePageRulesPriorities(ctx context.Context, requestCloudflare *zone.UpdatePageRulesPrioritiesRequestCloudflare) (*zone.PageRuleList, error) {
  644. //TODO 参数检查
  645. //设置HTTP请求
  646. client := &http.Client{}
  647. bytesData, err := json.Marshal(requestCloudflare.Data)
  648. if err != nil {
  649. return nil, err
  650. }
  651. req, err := http.NewRequest("PUT", "https://api.cloudflare.com/client/v4/zones/"+requestCloudflare.ZoneId+"/pagerules/priorities", bytes.NewReader(bytesData))
  652. if err != nil {
  653. return nil, err
  654. }
  655. req.Header.Add("X-Auth-Key", requestCloudflare.GetApiKey())
  656. req.Header.Add("X-Auth-Email", requestCloudflare.GetApiEmail())
  657. //执行HTTP请求
  658. resp, err := client.Do(req)
  659. if err != nil {
  660. return nil, err
  661. }
  662. defer func(Body io.ReadCloser) {
  663. _ = Body.Close()
  664. }(resp.Body)
  665. body, _ := ioutil.ReadAll(resp.Body)
  666. //解析HTTP返回数据
  667. var r cloudflare.PageRulesResponse
  668. err = json.Unmarshal(body, &r)
  669. //处理返回逻辑
  670. if err != nil {
  671. return nil, fmt.Errorf("%s: %w", "error unmarshalling the JSON response", err)
  672. }
  673. if r.Success != true {
  674. return nil, fmt.Errorf("%s", r.Errors)
  675. }
  676. rules := r.Result
  677. filterMap := lo.FilterMap[cloudflare.PageRule, *zone.PageRule](rules, func(rule cloudflare.PageRule, _ int) (*zone.PageRule, bool) {
  678. pageRule := Go2ProtoPageRule(&rule)
  679. return pageRule, true
  680. })
  681. return &zone.PageRuleList{PageRules: filterMap}, nil
  682. }
  683. // 默认开启Smarttiered cache
  684. func (s *ZoneServer) SetSmartTieredCache(ctx context.Context, requestCloudflare *zone.SetSmartTieredCacheRequestCloudflare) (*zone.SetSmartTieredCacheReplyCloudflare, error) {
  685. type ResponseType struct {
  686. Errors []interface{} `json:"errors"`
  687. Messages []interface{} `json:"messages"`
  688. Result interface{} `json:"result"`
  689. Success bool `json:"success"`
  690. }
  691. //设置HTTP请求
  692. client := &http.Client{}
  693. url := "https://api.cloudflare.com/client/v4/zones/" + requestCloudflare.ZoneId + "/cache/tiered_cache_smart_topology_enable"
  694. payload := strings.NewReader("{\n \"value\": \"on\"\n}")
  695. req, err := http.NewRequest("PATCH", url, payload)
  696. if err != nil {
  697. return nil, err
  698. }
  699. req.Header.Add("X-Auth-Key", requestCloudflare.GetApiKey())
  700. req.Header.Add("Content-Type", "application/json")
  701. req.Header.Add("X-Auth-Email", requestCloudflare.GetApiEmail())
  702. //执行HTTP请求
  703. resp, err := client.Do(req)
  704. if err != nil {
  705. return nil, err
  706. }
  707. defer func(Body io.ReadCloser) {
  708. _ = Body.Close()
  709. }(resp.Body)
  710. body, _ := ioutil.ReadAll(resp.Body)
  711. print(body)
  712. //解析HTTP返回数据
  713. var r ResponseType
  714. err = json.Unmarshal(body, &r)
  715. if err != nil {
  716. return nil, fmt.Errorf("%s: %w", "error unmarshalling the JSON response", err)
  717. }
  718. if r.Success != true {
  719. print(fmt.Errorf("%s", r.Errors))
  720. }
  721. return &zone.SetSmartTieredCacheReplyCloudflare{Enabled: r.Success}, nil
  722. }
  723. // 开启强制使用https
  724. func (s *ZoneServer) UpdateAlwaysUseHttps(ctx context.Context, requestCloudflare *zone.UpdateAlwaysUseHttpsRequestCloudflare) (*zone.UpdateAlwaysUseHttpsReplyCloudflare, error) {
  725. type ResponseType struct {
  726. Errors []interface{} `json:"errors"`
  727. Messages []interface{} `json:"messages"`
  728. Result interface{} `json:"result"`
  729. Success bool `json:"success"`
  730. }
  731. //设置HTTP请求
  732. client := &http.Client{}
  733. url := "https://api.cloudflare.com/client/v4/zones/" + requestCloudflare.ZoneId + "/settings/always_use_https"
  734. var payload io.Reader
  735. if requestCloudflare.Enabled {
  736. payload = strings.NewReader("{\n \"value\": \"on\"\n}")
  737. } else {
  738. payload = strings.NewReader("{\n \"value\": \"off\"\n}")
  739. }
  740. req, err := http.NewRequest("PATCH", url, payload)
  741. if err != nil {
  742. return nil, err
  743. }
  744. req.Header.Add("X-Auth-Key", requestCloudflare.GetApiKey())
  745. req.Header.Add("Content-Type", "application/json")
  746. req.Header.Add("X-Auth-Email", requestCloudflare.GetApiEmail())
  747. //执行HTTP请求
  748. resp, err := client.Do(req)
  749. if err != nil {
  750. return nil, err
  751. }
  752. defer func(Body io.ReadCloser) {
  753. _ = Body.Close()
  754. }(resp.Body)
  755. body, _ := ioutil.ReadAll(resp.Body)
  756. print(body)
  757. //解析HTTP返回数据
  758. var r ResponseType
  759. err = json.Unmarshal(body, &r)
  760. if err != nil {
  761. return nil, fmt.Errorf("%s: %w", "error unmarshalling the JSON response", err)
  762. }
  763. if r.Success != true {
  764. print(fmt.Errorf("%s", r.Errors))
  765. }
  766. return &zone.UpdateAlwaysUseHttpsReplyCloudflare{Success: r.Success}, nil
  767. }