base_auth.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. package controllers
  2. import (
  3. "encoding/json"
  4. "eta/eta_crawler/models"
  5. "eta/eta_crawler/utils"
  6. "fmt"
  7. "github.com/beego/beego/v2/server/web"
  8. "github.com/shopspring/decimal"
  9. "net/http"
  10. "net/url"
  11. "reflect"
  12. )
  13. type BaseAuthController struct {
  14. web.Controller
  15. }
  16. func (this *BaseAuthController) Prepare() {
  17. fmt.Println("enter prepare")
  18. method := this.Ctx.Input.Method()
  19. uri := this.Ctx.Input.URI()
  20. fmt.Println("Url:", uri)
  21. if method != "HEAD" {
  22. //if method == "POST" {
  23. // ok, errMsg := checkSign(this)
  24. // if !ok {
  25. // this.JSON(models.BaseResponse{Ret: 408, Msg: "签名错误!", ErrMsg: errMsg}, false, false)
  26. // this.StopRun()
  27. // return
  28. // }
  29. //} else {
  30. // this.JSON(models.BaseResponse{Ret: 408, Msg: "请求异常,请联系客服!", ErrMsg: "POST之外的请求,暂不支持"}, false, false)
  31. // this.StopRun()
  32. // return
  33. //}
  34. } else {
  35. this.JSON(models.BaseResponse{Ret: 408, Msg: "请求异常,请联系客服!", ErrMsg: "method:" + method}, false, false)
  36. this.StopRun()
  37. return
  38. }
  39. }
  40. //func checkSign(c *BaseAuthController) (ok bool, errMsg string) {
  41. // method := c.Ctx.Input.Method()
  42. // signData := make(map[string]string)
  43. //
  44. // switch method {
  45. // case "GET":
  46. // //requestBody = c.Ctx.Request.RequestURI
  47. // params := c.Ctx.Request.URL.Query()
  48. // signData = convertParam(params)
  49. // case "POST":
  50. // //requestBody, _ = url.QueryUnescape(string(c.Ctx.Input.RequestBody))
  51. //
  52. // //请求类型
  53. // contentType := c.Ctx.Request.Header.Get("content-type")
  54. // //fmt.Println("contentType:", contentType)
  55. // //fmt.Println("c.Ctx.Input.RequestBody:", string(c.Ctx.Input.RequestBody))
  56. //
  57. // switch contentType {
  58. // case "multipart/form-data":
  59. // //文件最大5M
  60. // err := c.Ctx.Request.ParseMultipartForm(-int64(5 << 20))
  61. // if err != nil {
  62. // errMsg = fmt.Sprintf("获取参数失败,%v", err)
  63. // return
  64. // }
  65. // params := c.Ctx.Request.Form
  66. // signData = convertParam(params)
  67. // case "application/x-www-form-urlencoded":
  68. // err := c.Ctx.Request.ParseForm()
  69. // if err != nil {
  70. // errMsg = fmt.Sprintf("获取参数失败,%v", err)
  71. // return
  72. // }
  73. // params := c.Ctx.Request.Form
  74. // signData = convertParam(params)
  75. // case "application/json":
  76. // //var v interface{}
  77. // params := make(map[string]interface{})
  78. // err := json.Unmarshal(c.Ctx.Input.RequestBody, &params)
  79. // if err != nil {
  80. // errMsg = fmt.Sprintf("获取参数失败,%v", err)
  81. // return
  82. // }
  83. // //fmt.Println("params:", params)
  84. //
  85. // signData = convertParamInterface(params)
  86. // //tmpV := v.(map[string]string)
  87. // //fmt.Println("tmpV:", tmpV)
  88. // //fmt.Sprintln("list type is v%", tmpV["list"])
  89. // default: //正常应该是其他方式获取解析的,暂时这么处理吧
  90. // err := c.Ctx.Request.ParseForm()
  91. // if err != nil {
  92. // errMsg = fmt.Sprintf("获取参数失败,%v", err)
  93. // return
  94. // }
  95. // params := c.Ctx.Request.Form
  96. // signData = convertParam(params)
  97. // }
  98. // }
  99. //
  100. // // 开始校验数据
  101. // ip := c.Ctx.Input.IP()
  102. // err := checkSignData(signData, ip)
  103. // if err != nil {
  104. // errMsg = fmt.Sprintf("签名校验失败,%v", err)
  105. // return
  106. // }
  107. //
  108. // ok = true
  109. // return
  110. //}
  111. func (c *BaseAuthController) ServeJSON(encoding ...bool) {
  112. // 方法处理完后,需要后置处理的业务逻辑
  113. //if handlerList, ok := AfterHandlerUrlMap[c.Ctx.Request.URL.Path]; ok {
  114. // for _, handler := range handlerList {
  115. // handler(c.Ctx.Input.RequestBody)
  116. // }
  117. //}
  118. //所有请求都做这么个处理吧,目前这边都是做编辑、刷新逻辑处理(新增的话,并没有指标id,不会有影响)
  119. var (
  120. hasIndent = false
  121. hasEncoding = false
  122. )
  123. if web.BConfig.RunMode == web.PROD {
  124. hasIndent = false
  125. }
  126. if len(encoding) > 0 && encoding[0] == true {
  127. hasEncoding = true
  128. }
  129. if c.Data["json"] == nil {
  130. go utils.SendEmail("异常提醒:", "接口:"+"URI:"+c.Ctx.Input.URI()+";无返回值", utils.EmailSendToUsers)
  131. return
  132. }
  133. baseRes := c.Data["json"].(*models.BaseResponse)
  134. if baseRes != nil && baseRes.Ret != 408 {
  135. //body, _ := json.Marshal(baseRes)
  136. //var requestBody string
  137. //method := c.Ctx.Input.Method()
  138. //if method == "GET" {
  139. // requestBody = c.Ctx.Request.RequestURI
  140. //} else {
  141. // requestBody, _ = url.QueryUnescape(string(c.Ctx.Input.RequestBody))
  142. //}
  143. //if baseRes.Ret != 200 && baseRes.IsSendEmail {
  144. // go utils.SendEmail(utils.APP_NAME_CN+"【"+utils.RunMode+"】"+"失败提醒", "URI:"+c.Ctx.Input.URI()+"<br/> "+"Params"+requestBody+" <br/>"+"ErrMsg:"+baseRes.ErrMsg+";<br/>Msg:"+baseRes.Msg+";<br/> Body:"+string(body)+"<br/>", utils.EmailSendToUsers)
  145. //}
  146. }
  147. c.JSON(c.Data["json"], hasIndent, hasEncoding)
  148. }
  149. func (c *BaseAuthController) JSON(data interface{}, hasIndent bool, coding bool) error {
  150. c.Ctx.Output.Header("Content-Type", "application/json; charset=utf-8")
  151. var content []byte
  152. var err error
  153. if hasIndent {
  154. content, err = json.MarshalIndent(data, "", " ")
  155. } else {
  156. content, err = json.Marshal(data)
  157. }
  158. if err != nil {
  159. http.Error(c.Ctx.Output.Context.ResponseWriter, err.Error(), http.StatusInternalServerError)
  160. return err
  161. }
  162. ip := c.Ctx.Input.IP()
  163. requestBody, err := url.QueryUnescape(string(c.Ctx.Input.RequestBody))
  164. if err != nil {
  165. requestBody = string(c.Ctx.Input.RequestBody)
  166. }
  167. if requestBody == "" {
  168. requestBody = c.Ctx.Input.URI()
  169. }
  170. c.logUri(content, requestBody, ip)
  171. if coding {
  172. content = []byte(utils.StringsToJSON(string(content)))
  173. }
  174. return c.Ctx.Output.Body(content)
  175. }
  176. // 将请求传入的数据格式转换成签名需要的格式
  177. func convertParam(params map[string][]string) (signData map[string]string) {
  178. signData = make(map[string]string)
  179. for key := range params {
  180. signData[key] = params[key][0]
  181. }
  182. return signData
  183. }
  184. // 将请求传入的数据格式转换成签名需要的格式(目前只能处理简单的类型,数组、对象暂不支持)
  185. func convertParamInterface(params map[string]interface{}) (signData map[string]string) {
  186. signData = make(map[string]string)
  187. for key := range params {
  188. val := ``
  189. //fmt.Println("key", key, ";val:", params[key], ";type:", reflect.TypeOf(params[key]))
  190. //signData[key] = params[key][0]
  191. tmpVal := params[key]
  192. switch reflect.TypeOf(tmpVal).Kind() {
  193. case reflect.String:
  194. val = fmt.Sprint(tmpVal)
  195. case reflect.Int, reflect.Int16, reflect.Int64, reflect.Int32, reflect.Int8:
  196. val = fmt.Sprint(tmpVal)
  197. case reflect.Uint, reflect.Uint32, reflect.Uint16, reflect.Uint8, reflect.Uint64:
  198. val = fmt.Sprint(tmpVal)
  199. case reflect.Bool:
  200. val = fmt.Sprint(tmpVal)
  201. case reflect.Float64:
  202. decimalNum := decimal.NewFromFloat(tmpVal.(float64))
  203. val = decimalNum.String()
  204. //val = strconv.FormatFloat(tmpVal.(float64), 'E', -1, 64) //float64
  205. case reflect.Float32:
  206. decimalNum := decimal.NewFromFloat32(tmpVal.(float32))
  207. val = decimalNum.String()
  208. }
  209. signData[key] = val
  210. }
  211. return signData
  212. }
  213. func (c *BaseAuthController) logUri(content []byte, requestBody, ip string) {
  214. utils.ApiLog.Info("uri:%s, requestBody:%s, responseBody:%s, ip:%s", c.Ctx.Input.URI(), requestBody, content, ip)
  215. return
  216. }