base_auth.go 7.3 KB

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