base_auth.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. package controllers
  2. import (
  3. "crypto/md5"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "github.com/shopspring/decimal"
  8. "hongze/hongze_open_api/models/custom"
  9. "hongze/hongze_open_api/models/tables/open_api_user"
  10. "hongze/hongze_open_api/utils"
  11. "math"
  12. "reflect"
  13. "sort"
  14. "strconv"
  15. "strings"
  16. "time"
  17. )
  18. // BaseAuth 需要授权token的基类
  19. type BaseAuth struct {
  20. BaseCommon
  21. AdminWx *custom.AdminWx `description:"管理员信息"`
  22. Token string `description:"用户token"`
  23. StartSize int `description:"开始数量"`
  24. StartPage int `description:"开始页码"`
  25. PageSize int `description:"每页数量"`
  26. }
  27. func (c *BaseAuth) Prepare() {
  28. //var requestBody string
  29. signData := make(map[string]string)
  30. method := c.Ctx.Input.Method()
  31. var pageSize, currentIndex int
  32. switch method {
  33. case "GET":
  34. //requestBody = c.Ctx.Request.RequestURI
  35. params := c.Ctx.Request.URL.Query()
  36. signData = convertParam(params)
  37. pageSize, _ = c.GetInt("_page_size")
  38. currentIndex, _ = c.GetInt("_page")
  39. case "POST":
  40. //requestBody, _ = url.QueryUnescape(string(c.Ctx.Input.RequestBody))
  41. //请求类型
  42. contentType := c.Ctx.Request.Header.Get("content-type")
  43. //fmt.Println("contentType:", contentType)
  44. //fmt.Println("c.Ctx.Input.RequestBody:", string(c.Ctx.Input.RequestBody))
  45. switch contentType {
  46. case "multipart/form-data":
  47. //文件最大5M
  48. err := c.Ctx.Request.ParseMultipartForm(-int64(5 << 20))
  49. if err != nil {
  50. c.FailWithMessage(fmt.Sprintf("获取参数失败,%v", err))
  51. //response.FailWithMessage(fmt.Sprintf("获取参数失败,%v", err), c)
  52. //c.Abort()
  53. return
  54. }
  55. params := c.Ctx.Request.Form
  56. signData = convertParam(params)
  57. case "application/x-www-form-urlencoded":
  58. err := c.Ctx.Request.ParseForm()
  59. if err != nil {
  60. c.FailWithMessage(fmt.Sprintf("获取参数失败,%v", err))
  61. return
  62. }
  63. params := c.Ctx.Request.Form
  64. signData = convertParam(params)
  65. case "application/json":
  66. //var v interface{}
  67. params := make(map[string]interface{})
  68. err := json.Unmarshal(c.Ctx.Input.RequestBody, &params)
  69. if err != nil {
  70. // handle error
  71. //fmt.Println("err json:", err)
  72. c.FailWithMessage(fmt.Sprintf("获取参数失败,%v", err))
  73. return
  74. }
  75. //fmt.Println("params:", params)
  76. signData = convertParamInterface(params)
  77. //tmpV := v.(map[string]string)
  78. //fmt.Println("tmpV:", tmpV)
  79. //fmt.Sprintln("list type is v%", tmpV["list"])
  80. default: //正常应该是其他方式获取解析的,暂时这么处理吧
  81. err := c.Ctx.Request.ParseForm()
  82. if err != nil {
  83. c.FailWithMessage(fmt.Sprintf("获取参数失败,%v", err))
  84. return
  85. }
  86. params := c.Ctx.Request.Form
  87. signData = convertParam(params)
  88. }
  89. }
  90. //fmt.Println("signData:", signData)
  91. //页码数
  92. var startSize int
  93. if pageSize <= 0 {
  94. pageSize = utils.PageSize20
  95. }
  96. //如果超过最大分页数,那么就是按照最大分页数返回
  97. if pageSize > utils.PageMaxSize {
  98. pageSize = utils.PageMaxSize
  99. }
  100. if currentIndex <= 0 {
  101. currentIndex = 1
  102. }
  103. startSize = utils.StartIndex(currentIndex, pageSize)
  104. c.StartSize = startSize
  105. c.PageSize = pageSize
  106. c.StartPage = currentIndex
  107. ip := c.Ctx.Input.IP()
  108. //获取签名秘钥
  109. //key := global.GVA_CONFIG.SignKey.Agent
  110. ////签名校验
  111. err := checkSign(signData, ip)
  112. if err != nil {
  113. c.SignError(fmt.Sprintf("签名校验失败,%v", err))
  114. return
  115. }
  116. uri := c.Ctx.Input.URI()
  117. utils.FileLog.Info(fmt.Sprintf("URI:%s", uri))
  118. }
  119. // 将请求传入的数据格式转换成签名需要的格式
  120. func convertParam(params map[string][]string) (signData map[string]string) {
  121. signData = make(map[string]string)
  122. for key := range params {
  123. signData[key] = params[key][0]
  124. }
  125. return signData
  126. }
  127. // 将请求传入的数据格式转换成签名需要的格式(目前只能处理简单的类型,数组、对象暂不支持)
  128. func convertParamInterface(params map[string]interface{}) (signData map[string]string) {
  129. signData = make(map[string]string)
  130. for key := range params {
  131. val := ``
  132. //fmt.Println("key", key, ";val:", params[key], ";type:", reflect.TypeOf(params[key]))
  133. //signData[key] = params[key][0]
  134. tmpVal := params[key]
  135. switch reflect.TypeOf(tmpVal).Kind() {
  136. case reflect.String:
  137. val = fmt.Sprint(tmpVal)
  138. case reflect.Int, reflect.Int16, reflect.Int64, reflect.Int32, reflect.Int8:
  139. val = fmt.Sprint(tmpVal)
  140. case reflect.Uint, reflect.Uint32, reflect.Uint16, reflect.Uint8, reflect.Uint64:
  141. val = fmt.Sprint(tmpVal)
  142. case reflect.Bool:
  143. val = fmt.Sprint(tmpVal)
  144. case reflect.Float64:
  145. decimalNum := decimal.NewFromFloat(tmpVal.(float64))
  146. val = decimalNum.String()
  147. //val = strconv.FormatFloat(tmpVal.(float64), 'E', -1, 64) //float64
  148. case reflect.Float32:
  149. decimalNum := decimal.NewFromFloat32(tmpVal.(float32))
  150. val = decimalNum.String()
  151. }
  152. signData[key] = val
  153. }
  154. return signData
  155. }
  156. // 请求参数签名校验
  157. func checkSign(postData map[string]string, ip string) (err error) {
  158. isSandbox := postData["is_sandbox"]
  159. //如果是测试环境,且是沙箱环境的话,那么绕过测试
  160. if utils.RunMode == "debug" && isSandbox != "" {
  161. return
  162. }
  163. appid := postData["appid"]
  164. if appid == "" {
  165. err = errors.New("参数异常,缺少appid")
  166. return
  167. }
  168. openApiUserInfo, tmpErr := open_api_user.GetByAppid(appid)
  169. if tmpErr != nil {
  170. if tmpErr.Error() == utils.ErrNoRow() {
  171. err = errors.New("appid异常,请联系管理员")
  172. } else {
  173. err = errors.New("系统异常,请联系管理员")
  174. }
  175. return
  176. }
  177. if openApiUserInfo == nil {
  178. err = errors.New("系统异常,请联系管理员")
  179. return
  180. }
  181. //如果有ip限制,那么就添加ip
  182. if openApiUserInfo.Ip != "" {
  183. if !strings.Contains(openApiUserInfo.Ip, ip) {
  184. err = errors.New(fmt.Sprintf("无权限访问该接口,ip:%v,请联系管理员", ip))
  185. return
  186. }
  187. }
  188. //接口提交的签名字符串
  189. ownSign := postData["sign"]
  190. if ownSign == "" {
  191. err = errors.New("参数异常,缺少签名字符串")
  192. return
  193. }
  194. if postData["nonce_str"] == "" {
  195. err = errors.New("参数异常,缺少随机字符串")
  196. return
  197. }
  198. if postData["timestamp"] == "" {
  199. err = errors.New("参数异常,缺少时间戳")
  200. return
  201. } else {
  202. timeUnix := time.Now().Unix() //当前格林威治时间,int64类型
  203. //将接口传入的时间做转换
  204. timestamp, timeErr := strconv.ParseInt(postData["timestamp"], 10, 64)
  205. if timeErr != nil {
  206. err = errors.New("参数异常,时间戳格式异常")
  207. return
  208. }
  209. if math.Abs(float64(timeUnix-timestamp)) > 300 {
  210. err = errors.New("当前时间异常,请调整设备时间与北京时间一致")
  211. return
  212. }
  213. }
  214. //先取出除sign外的所有的提交的参数key
  215. var keys []string
  216. for k := range postData {
  217. if k != "sign" {
  218. keys = append(keys, k)
  219. }
  220. }
  221. //1,根据参数名称的ASCII码表的顺序排序
  222. sort.Strings(keys)
  223. //2 根据排序后的参数名称,取出对应的值,并拼接字符串
  224. var signStr string
  225. for _, v := range keys {
  226. signStr += v + "=" + postData[v] + "&"
  227. }
  228. //3,全转小写(md5(拼装的字符串后+分配给你的app_secret))
  229. //sign := strings.ToLower(fmt.Sprintf("%x", md5.Sum([]byte(strings.Trim(signStr, "&")+key))))
  230. //md5.Sum([]byte(signStr+"key="+key)) 这是md5加密出来后的每个字符的ascall码,需要再转换成对应的字符
  231. //3,全转大写(md5(拼装的字符串后+分配给你的app_secret))
  232. sign := strings.ToUpper(fmt.Sprintf("%x", md5.Sum([]byte(signStr+"secret="+openApiUserInfo.Secret))))
  233. if sign != ownSign {
  234. utils.ApiLog.Println(fmt.Sprintf("签名校验异常,签名字符串:%v;服务端签名值:%v", signStr, sign))
  235. return errors.New("签名校验异常,请核实签名")
  236. }
  237. return nil
  238. }