base_auth.go 5.4 KB

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