base_auth.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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. "hongze/hz_data_api/models"
  18. "hongze/hz_data_api/utils"
  19. "github.com/rdlucklib/rdluck_tools/log"
  20. )
  21. var apiLog *log.Log
  22. func init() {
  23. if utils.RunMode == "release" {
  24. logDir := `/data/rdlucklog/` + utils.APP_NAME_EN
  25. apiLog = log.Init("20060102.api", logDir)
  26. } else {
  27. apiLog = log.Init("20060102.api")
  28. }
  29. }
  30. type BaseAuthController struct {
  31. web.Controller
  32. }
  33. func (this *BaseAuthController) Prepare() {
  34. fmt.Println("enter prepare")
  35. method := this.Ctx.Input.Method()
  36. uri := this.Ctx.Input.URI()
  37. fmt.Println("Url:", uri)
  38. if method != "HEAD" {
  39. if method == "POST" {
  40. ok, errMsg := checkSign(this)
  41. if !ok {
  42. this.JSON(models.BaseResponse{Ret: 408, Msg: "签名错误!", ErrMsg: errMsg}, false, false)
  43. this.StopRun()
  44. return
  45. }
  46. } else {
  47. this.JSON(models.BaseResponse{Ret: 408, Msg: "请求异常,请联系客服!", ErrMsg: "POST之外的请求,暂不支持"}, false, false)
  48. this.StopRun()
  49. return
  50. }
  51. } else {
  52. this.JSON(models.BaseResponse{Ret: 408, Msg: "请求异常,请联系客服!", ErrMsg: "method:" + method}, false, false)
  53. this.StopRun()
  54. return
  55. }
  56. }
  57. func checkSign(c *BaseAuthController) (ok bool, errMsg string) {
  58. method := c.Ctx.Input.Method()
  59. signData := make(map[string]string)
  60. switch method {
  61. case "GET":
  62. //requestBody = c.Ctx.Request.RequestURI
  63. params := c.Ctx.Request.URL.Query()
  64. signData = convertParam(params)
  65. case "POST":
  66. //requestBody, _ = url.QueryUnescape(string(c.Ctx.Input.RequestBody))
  67. //请求类型
  68. contentType := c.Ctx.Request.Header.Get("content-type")
  69. //fmt.Println("contentType:", contentType)
  70. //fmt.Println("c.Ctx.Input.RequestBody:", string(c.Ctx.Input.RequestBody))
  71. switch contentType {
  72. case "multipart/form-data":
  73. //文件最大5M
  74. err := c.Ctx.Request.ParseMultipartForm(-int64(5 << 20))
  75. if err != nil {
  76. errMsg = fmt.Sprintf("获取参数失败,%v", err)
  77. return
  78. }
  79. params := c.Ctx.Request.Form
  80. signData = convertParam(params)
  81. case "application/x-www-form-urlencoded":
  82. err := c.Ctx.Request.ParseForm()
  83. if err != nil {
  84. errMsg = fmt.Sprintf("获取参数失败,%v", err)
  85. return
  86. }
  87. params := c.Ctx.Request.Form
  88. signData = convertParam(params)
  89. case "application/json":
  90. //var v interface{}
  91. params := make(map[string]interface{})
  92. err := json.Unmarshal(c.Ctx.Input.RequestBody, &params)
  93. if err != nil {
  94. errMsg = fmt.Sprintf("获取参数失败,%v", err)
  95. return
  96. }
  97. //fmt.Println("params:", params)
  98. signData = convertParamInterface(params)
  99. //tmpV := v.(map[string]string)
  100. //fmt.Println("tmpV:", tmpV)
  101. //fmt.Sprintln("list type is v%", tmpV["list"])
  102. default: //正常应该是其他方式获取解析的,暂时这么处理吧
  103. err := c.Ctx.Request.ParseForm()
  104. if err != nil {
  105. errMsg = fmt.Sprintf("获取参数失败,%v", err)
  106. return
  107. }
  108. params := c.Ctx.Request.Form
  109. signData = convertParam(params)
  110. }
  111. }
  112. // 开始校验数据
  113. ip := c.Ctx.Input.IP()
  114. err := checkSignData(signData, ip)
  115. if err != nil {
  116. errMsg = fmt.Sprintf("签名校验失败,%v", err)
  117. return
  118. }
  119. ok = true
  120. return
  121. }
  122. func (c *BaseAuthController) ServeJSON(encoding ...bool) {
  123. // 方法处理完后,需要后置处理的业务逻辑
  124. //if handlerList, ok := AfterHandlerUrlMap[c.Ctx.Request.URL.Path]; ok {
  125. // for _, handler := range handlerList {
  126. // handler(c.Ctx.Input.RequestBody)
  127. // }
  128. //}
  129. //所有请求都做这么个处理吧,目前这边都是做编辑、刷新逻辑处理(新增的话,并没有指标id,不会有影响)
  130. var (
  131. hasIndent = false
  132. hasEncoding = false
  133. )
  134. if web.BConfig.RunMode == web.PROD {
  135. hasIndent = false
  136. }
  137. if len(encoding) > 0 && encoding[0] == true {
  138. hasEncoding = true
  139. }
  140. if c.Data["json"] == nil {
  141. go utils.SendEmail("异常提醒:", "接口:"+"URI:"+c.Ctx.Input.URI()+";无返回值", utils.EmailSendToUsers)
  142. return
  143. }
  144. baseRes := c.Data["json"].(*models.BaseResponse)
  145. if baseRes != nil && baseRes.Ret != 408 {
  146. body, _ := json.Marshal(baseRes)
  147. var requestBody string
  148. method := c.Ctx.Input.Method()
  149. if method == "GET" {
  150. requestBody = c.Ctx.Request.RequestURI
  151. } else {
  152. requestBody, _ = url.QueryUnescape(string(c.Ctx.Input.RequestBody))
  153. }
  154. if baseRes.Ret != 200 && baseRes.IsSendEmail {
  155. 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)
  156. }
  157. }
  158. c.JSON(c.Data["json"], hasIndent, hasEncoding)
  159. }
  160. func (c *BaseAuthController) JSON(data interface{}, hasIndent bool, coding bool) error {
  161. c.Ctx.Output.Header("Content-Type", "application/json; charset=utf-8")
  162. var content []byte
  163. var err error
  164. if hasIndent {
  165. content, err = json.MarshalIndent(data, "", " ")
  166. } else {
  167. content, err = json.Marshal(data)
  168. }
  169. if err != nil {
  170. http.Error(c.Ctx.Output.Context.ResponseWriter, err.Error(), http.StatusInternalServerError)
  171. return err
  172. }
  173. ip := c.Ctx.Input.IP()
  174. requestBody, err := url.QueryUnescape(string(c.Ctx.Input.RequestBody))
  175. if err != nil {
  176. requestBody = string(c.Ctx.Input.RequestBody)
  177. }
  178. if requestBody == "" {
  179. requestBody = c.Ctx.Input.URI()
  180. }
  181. apiLog.Println("请求地址:", c.Ctx.Input.URI(), "RequestBody:", requestBody, "ResponseBody", string(content), "IP:", ip)
  182. if coding {
  183. content = []byte(utils.StringsToJSON(string(content)))
  184. }
  185. return c.Ctx.Output.Body(content)
  186. }
  187. // 将请求传入的数据格式转换成签名需要的格式
  188. func convertParam(params map[string][]string) (signData map[string]string) {
  189. signData = make(map[string]string)
  190. for key := range params {
  191. signData[key] = params[key][0]
  192. }
  193. return signData
  194. }
  195. // 将请求传入的数据格式转换成签名需要的格式(目前只能处理简单的类型,数组、对象暂不支持)
  196. func convertParamInterface(params map[string]interface{}) (signData map[string]string) {
  197. signData = make(map[string]string)
  198. for key := range params {
  199. val := ``
  200. //fmt.Println("key", key, ";val:", params[key], ";type:", reflect.TypeOf(params[key]))
  201. //signData[key] = params[key][0]
  202. tmpVal := params[key]
  203. switch reflect.TypeOf(tmpVal).Kind() {
  204. case reflect.String:
  205. val = fmt.Sprint(tmpVal)
  206. case reflect.Int, reflect.Int16, reflect.Int64, reflect.Int32, reflect.Int8:
  207. val = fmt.Sprint(tmpVal)
  208. case reflect.Uint, reflect.Uint32, reflect.Uint16, reflect.Uint8, reflect.Uint64:
  209. val = fmt.Sprint(tmpVal)
  210. case reflect.Bool:
  211. val = fmt.Sprint(tmpVal)
  212. case reflect.Float64:
  213. decimalNum := decimal.NewFromFloat(tmpVal.(float64))
  214. val = decimalNum.String()
  215. //val = strconv.FormatFloat(tmpVal.(float64), 'E', -1, 64) //float64
  216. case reflect.Float32:
  217. decimalNum := decimal.NewFromFloat32(tmpVal.(float32))
  218. val = decimalNum.String()
  219. }
  220. signData[key] = val
  221. }
  222. return signData
  223. }
  224. // checkSignData 请求参数签名校验
  225. func checkSignData(postData map[string]string, ip string) (err error) {
  226. isSandbox := postData["is_sandbox"]
  227. //如果是测试环境,且是沙箱环境的话,那么绕过测试
  228. if utils.RunMode == "debug" && isSandbox != "" {
  229. return
  230. }
  231. appid := postData["appid"]
  232. if appid == "" {
  233. err = errors.New("参数异常,缺少appid")
  234. return
  235. }
  236. openApiUserInfo, tmpErr := models.GetByAppid(appid)
  237. if tmpErr != nil {
  238. if tmpErr.Error() == utils.ErrNoRow() {
  239. err = errors.New("appid异常,请联系管理员")
  240. } else {
  241. err = errors.New("系统异常,请联系管理员")
  242. }
  243. return
  244. }
  245. if openApiUserInfo == nil {
  246. err = errors.New("系统异常,请联系管理员")
  247. return
  248. }
  249. //如果有ip限制,那么就添加ip
  250. if openApiUserInfo.Ip != "" {
  251. if !strings.Contains(openApiUserInfo.Ip, ip) {
  252. err = errors.New(fmt.Sprintf("无权限访问该接口,ip:%v,请联系管理员", ip))
  253. return
  254. }
  255. }
  256. //接口提交的签名字符串
  257. ownSign := postData["sign"]
  258. if ownSign == "" {
  259. err = errors.New("参数异常,缺少签名字符串")
  260. return
  261. }
  262. if postData["nonce_str"] == "" {
  263. err = errors.New("参数异常,缺少随机字符串")
  264. return
  265. }
  266. if postData["timestamp"] == "" {
  267. err = errors.New("参数异常,缺少时间戳")
  268. return
  269. } else {
  270. timeUnix := time.Now().Unix() //当前格林威治时间,int64类型
  271. //将接口传入的时间做转换
  272. timestamp, timeErr := strconv.ParseInt(postData["timestamp"], 10, 64)
  273. if timeErr != nil {
  274. err = errors.New("参数异常,时间戳格式异常")
  275. return
  276. }
  277. if math.Abs(float64(timeUnix-timestamp)) > 300 {
  278. err = errors.New("当前时间异常,请调整设备时间与北京时间一致")
  279. return
  280. }
  281. }
  282. //先取出除sign外的所有的提交的参数key
  283. var keys []string
  284. for k := range postData {
  285. if k != "sign" {
  286. keys = append(keys, k)
  287. }
  288. }
  289. //1,根据参数名称的ASCII码表的顺序排序
  290. sort.Strings(keys)
  291. //2 根据排序后的参数名称,取出对应的值,并拼接字符串
  292. var signStr string
  293. for _, v := range keys {
  294. signStr += v + "=" + postData[v] + "&"
  295. }
  296. //3,全转小写(md5(拼装的字符串后+分配给你的app_secret))
  297. //sign := strings.ToLower(fmt.Sprintf("%x", md5.Sum([]byte(strings.Trim(signStr, "&")+key))))
  298. //md5.Sum([]byte(signStr+"key="+key)) 这是md5加密出来后的每个字符的ascall码,需要再转换成对应的字符
  299. //3,全转大写(md5(拼装的字符串后+分配给你的app_secret))
  300. sign := strings.ToUpper(fmt.Sprintf("%x", md5.Sum([]byte(signStr+"secret="+openApiUserInfo.Secret))))
  301. if sign != ownSign {
  302. utils.FileLog.Info(fmt.Sprintf("签名校验异常,签名字符串:%v;服务端签名值:%v", signStr, sign))
  303. return errors.New("签名校验异常,请核实签名")
  304. }
  305. return nil
  306. }