base_auth.go 7.4 KB

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