base_auth.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  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. if currentIndex <= 0 {
  67. currentIndex = 1
  68. }
  69. startSize = utils.StartIndex(currentIndex, pageSize)
  70. c.StartSize = startSize
  71. c.PageSize = pageSize
  72. c.StartPage = currentIndex
  73. ip := c.Ctx.Input.IP()
  74. //获取签名秘钥
  75. //key := global.GVA_CONFIG.SignKey.Agent
  76. ////签名校验
  77. err := checkSign(signData,ip)
  78. if err != nil {
  79. c.SignError(fmt.Sprintf("签名校验失败,%v", err))
  80. return
  81. }
  82. uri := c.Ctx.Input.URI()
  83. utils.FileLog.Info(fmt.Sprintf("URI:%s", uri))
  84. }
  85. //将请求传入的数据格式转换成签名需要的格式
  86. func convertParam(params map[string][]string)(signData map[string]string) {
  87. signData = make(map[string]string)
  88. for key := range params {
  89. signData[key] = params[key][0]
  90. }
  91. return signData
  92. }
  93. //请求参数签名校验
  94. func checkSign(postData map[string]string,ip string) (err error){
  95. isSandbox := postData["is_sandbox"]
  96. //如果是测试环境,且是沙箱环境的话,那么绕过测试
  97. if utils.RunMode == "debug" && isSandbox != "" {
  98. return
  99. }
  100. appid :=postData["appid"]
  101. if appid == "" {
  102. err = errors.New("参数异常,缺少appid")
  103. return
  104. }
  105. openApiUserInfo,tmpErr:= open_api_user.GetByAppid(appid)
  106. if tmpErr != nil{
  107. if tmpErr.Error() == utils.ErrNoRow(){
  108. err = errors.New("appid异常,请联系管理员")
  109. }else{
  110. err = errors.New("系统异常,请联系管理员")
  111. }
  112. return
  113. }
  114. if openApiUserInfo == nil{
  115. err = errors.New("系统异常,请联系管理员")
  116. return
  117. }
  118. //如果有ip限制,那么就添加ip
  119. if openApiUserInfo.Ip != ""{
  120. if !strings.Contains(openApiUserInfo.Ip,ip){
  121. err = errors.New(fmt.Sprintf("无权限访问该接口,ip:%v,请联系管理员",ip))
  122. return
  123. }
  124. }
  125. //接口提交的签名字符串
  126. ownSign := postData["sign"]
  127. if ownSign == "" {
  128. err = errors.New("参数异常,缺少签名字符串")
  129. return
  130. }
  131. if postData["nonce_str"] == "" {
  132. err = errors.New("参数异常,缺少随机字符串")
  133. return
  134. }
  135. if postData["timestamp"] == "" {
  136. err = errors.New("参数异常,缺少时间戳")
  137. return
  138. }else{
  139. timeUnix := time.Now().Unix() //当前格林威治时间,int64类型
  140. //将接口传入的时间做转换
  141. timestamp, timeErr := strconv.ParseInt(postData["timestamp"], 10, 64)
  142. if timeErr != nil{
  143. err = errors.New("参数异常,时间戳格式异常")
  144. return
  145. }
  146. if math.Abs(float64(timeUnix - timestamp)) > 300 {
  147. err = errors.New("当前时间异常,请调整设备时间与北京时间一致")
  148. return
  149. }
  150. }
  151. //先取出除sign外的所有的提交的参数key
  152. var keys []string
  153. for k, _ := range postData {
  154. if k != "sign" {
  155. keys = append(keys, k)
  156. }
  157. }
  158. //1,根据参数名称的ASCII码表的顺序排序
  159. sort.Strings(keys)
  160. //2 根据排序后的参数名称,取出对应的值,并拼接字符串
  161. var signStr string
  162. for _, v := range keys {
  163. signStr += v + "=" + postData[v] + "&"
  164. }
  165. //3,全转小写(md5(拼装的字符串后+分配给你的app_secret))
  166. //sign := strings.ToLower(fmt.Sprintf("%x", md5.Sum([]byte(strings.Trim(signStr, "&")+key))))
  167. //md5.Sum([]byte(signStr+"key="+key)) 这是md5加密出来后的每个字符的ascall码,需要再转换成对应的字符
  168. //3,全转大写(md5(拼装的字符串后+分配给你的app_secret))
  169. sign := strings.ToUpper(fmt.Sprintf("%x", md5.Sum([]byte(signStr+"secret="+openApiUserInfo.Secret))))
  170. if sign != ownSign {
  171. utils.ApiLog.Println(fmt.Sprintf("签名校验异常,签名字符串:%v;服务端签名值:%v",signStr,sign))
  172. return errors.New("签名校验异常,请核实签名")
  173. }
  174. return nil
  175. }