base_auth.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. package controllers
  2. import (
  3. "crypto/md5"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "github.com/beego/beego/v2/server/web"
  8. "github.com/shopspring/decimal"
  9. "math"
  10. "net/http"
  11. "net/url"
  12. "reflect"
  13. "sort"
  14. "strconv"
  15. "strings"
  16. "time"
  17. "eta/eta_data_push/models"
  18. "eta/eta_data_push/utils"
  19. )
  20. type BaseAuthController struct {
  21. web.Controller
  22. }
  23. func (this *BaseAuthController) Prepare() {
  24. fmt.Println("enter prepare")
  25. method := this.Ctx.Input.Method()
  26. uri := this.Ctx.Input.URI()
  27. fmt.Println("Url:", uri)
  28. if method != "HEAD" {
  29. if method == "POST" {
  30. ok, errMsg := checkSign(this)
  31. if !ok {
  32. this.JSON(models.BaseResponse{Ret: 408, Msg: "签名错误!", ErrMsg: errMsg}, false, false)
  33. this.StopRun()
  34. return
  35. }
  36. } else {
  37. this.JSON(models.BaseResponse{Ret: 408, Msg: "请求异常,请联系客服!", ErrMsg: "POST之外的请求,暂不支持"}, false, false)
  38. this.StopRun()
  39. return
  40. }
  41. } else {
  42. this.JSON(models.BaseResponse{Ret: 408, Msg: "请求异常,请联系客服!", ErrMsg: "method:" + method}, false, false)
  43. this.StopRun()
  44. return
  45. }
  46. }
  47. func checkSign(c *BaseAuthController) (ok bool, errMsg string) {
  48. method := c.Ctx.Input.Method()
  49. signData := make(map[string]string)
  50. switch method {
  51. case "GET":
  52. //requestBody = c.Ctx.Request.RequestURI
  53. params := c.Ctx.Request.URL.Query()
  54. signData = convertParam(params)
  55. case "POST":
  56. //requestBody, _ = url.QueryUnescape(string(c.Ctx.Input.RequestBody))
  57. //请求类型
  58. contentType := c.Ctx.Request.Header.Get("content-type")
  59. //fmt.Println("contentType:", contentType)
  60. //fmt.Println("c.Ctx.Input.RequestBody:", string(c.Ctx.Input.RequestBody))
  61. switch contentType {
  62. case "multipart/form-data":
  63. //文件最大5M
  64. err := c.Ctx.Request.ParseMultipartForm(-int64(5 << 20))
  65. if err != nil {
  66. errMsg = fmt.Sprintf("获取参数失败,%v", err)
  67. return
  68. }
  69. params := c.Ctx.Request.Form
  70. signData = convertParam(params)
  71. case "application/x-www-form-urlencoded":
  72. err := c.Ctx.Request.ParseForm()
  73. if err != nil {
  74. errMsg = fmt.Sprintf("获取参数失败,%v", err)
  75. return
  76. }
  77. params := c.Ctx.Request.Form
  78. signData = convertParam(params)
  79. case "application/json":
  80. //var v interface{}
  81. params := make(map[string]interface{})
  82. err := json.Unmarshal(c.Ctx.Input.RequestBody, &params)
  83. if err != nil {
  84. errMsg = fmt.Sprintf("获取参数失败,%v", err)
  85. return
  86. }
  87. //fmt.Println("params:", params)
  88. signData = convertParamInterface(params)
  89. //tmpV := v.(map[string]string)
  90. //fmt.Println("tmpV:", tmpV)
  91. //fmt.Sprintln("list type is v%", tmpV["list"])
  92. default: //正常应该是其他方式获取解析的,暂时这么处理吧
  93. err := c.Ctx.Request.ParseForm()
  94. if err != nil {
  95. errMsg = fmt.Sprintf("获取参数失败,%v", err)
  96. return
  97. }
  98. params := c.Ctx.Request.Form
  99. signData = convertParam(params)
  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. 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(content, 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. // checkSignData 请求参数签名校验
  215. func checkSignData(postData map[string]string, ip string) (err error) {
  216. isSandbox := postData["is_sandbox"]
  217. //如果是测试环境,且是沙箱环境的话,那么绕过测试
  218. if utils.RunMode == "debug" && isSandbox != "" {
  219. return
  220. }
  221. appid := postData["appid"]
  222. if appid == "" {
  223. err = errors.New("参数异常,缺少appid")
  224. return
  225. }
  226. openApiUserInfo, tmpErr := models.GetByAppid(appid)
  227. if tmpErr != nil {
  228. if tmpErr.Error() == utils.ErrNoRow() {
  229. err = errors.New("appid异常,请联系管理员")
  230. } else {
  231. err = errors.New("系统异常,请联系管理员")
  232. }
  233. return
  234. }
  235. if openApiUserInfo == nil {
  236. err = errors.New("系统异常,请联系管理员")
  237. return
  238. }
  239. //如果有ip限制,那么就添加ip
  240. if openApiUserInfo.Ip != "" {
  241. if !strings.Contains(openApiUserInfo.Ip, ip) {
  242. err = errors.New(fmt.Sprintf("无权限访问该接口,ip:%v,请联系管理员", ip))
  243. return
  244. }
  245. }
  246. //接口提交的签名字符串
  247. ownSign := postData["sign"]
  248. if ownSign == "" {
  249. err = errors.New("参数异常,缺少签名字符串")
  250. return
  251. }
  252. if postData["nonce_str"] == "" {
  253. err = errors.New("参数异常,缺少随机字符串")
  254. return
  255. }
  256. if postData["timestamp"] == "" {
  257. err = errors.New("参数异常,缺少时间戳")
  258. return
  259. } else {
  260. timeUnix := time.Now().Unix() //当前格林威治时间,int64类型
  261. //将接口传入的时间做转换
  262. timestamp, timeErr := strconv.ParseInt(postData["timestamp"], 10, 64)
  263. if timeErr != nil {
  264. err = errors.New("参数异常,时间戳格式异常")
  265. return
  266. }
  267. if math.Abs(float64(timeUnix-timestamp)) > 300 {
  268. err = errors.New("当前时间异常,请调整设备时间与北京时间一致")
  269. return
  270. }
  271. }
  272. //先取出除sign外的所有的提交的参数key
  273. var keys []string
  274. for k := range postData {
  275. if k != "sign" {
  276. keys = append(keys, k)
  277. }
  278. }
  279. //1,根据参数名称的ASCII码表的顺序排序
  280. sort.Strings(keys)
  281. //2 根据排序后的参数名称,取出对应的值,并拼接字符串
  282. var signStr string
  283. for _, v := range keys {
  284. signStr += v + "=" + postData[v] + "&"
  285. }
  286. //3,全转小写(md5(拼装的字符串后+分配给你的app_secret))
  287. //sign := strings.ToLower(fmt.Sprintf("%x", md5.Sum([]byte(strings.Trim(signStr, "&")+key))))
  288. //md5.Sum([]byte(signStr+"key="+key)) 这是md5加密出来后的每个字符的ascall码,需要再转换成对应的字符
  289. //3,全转大写(md5(拼装的字符串后+分配给你的app_secret))
  290. sign := strings.ToUpper(fmt.Sprintf("%x", md5.Sum([]byte(signStr+"secret="+openApiUserInfo.Secret))))
  291. if sign != ownSign {
  292. utils.FileLog.Info(fmt.Sprintf("签名校验异常,签名字符串:%v;服务端签名值:%v", signStr, sign))
  293. return errors.New("签名校验异常,请核实签名")
  294. }
  295. return nil
  296. }
  297. func (c *BaseAuthController) logUri(content []byte, requestBody, ip string) {
  298. utils.ApiLog.Info("uri:%s, requestBody:%s, responseBody:%s, ip:%s", c.Ctx.Input.URI(), requestBody, content, ip)
  299. return
  300. }