sign.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package http
  2. import (
  3. "bytes"
  4. "crypto/md5"
  5. "encoding/hex"
  6. "net/url"
  7. "sort"
  8. "strings"
  9. "go-common/app/service/main/passport-game/model"
  10. "go-common/app/service/main/passport-game/service"
  11. "go-common/library/ecode"
  12. bm "go-common/library/net/http/blademaster"
  13. )
  14. // VerifySign verify sign.
  15. func verifySign(c *bm.Context, s *service.Service) (res *model.App, err error) {
  16. var (
  17. r = c.Request
  18. query = r.Form
  19. )
  20. if r.Method == "POST" {
  21. // Give priority to sign in url query, otherwise check sign in post form.
  22. p := c.Request.URL.Query()
  23. if p.Get("sign") != "" {
  24. query = p
  25. }
  26. }
  27. if query.Get("ts") == "" {
  28. err = ecode.RequestErr
  29. return
  30. }
  31. appKey := query.Get("appkey")
  32. if appKey == "" {
  33. err = ecode.RequestErr
  34. return
  35. }
  36. app, ok := s.APP(appKey)
  37. if !ok {
  38. err = ecode.AppKeyInvalid
  39. return
  40. }
  41. secret := app.AppSecret
  42. tmp := encodeQuery(query)
  43. if strings.IndexByte(tmp, '+') > -1 {
  44. tmp = strings.Replace(tmp, "+", "%20", -1)
  45. }
  46. mh := md5.Sum([]byte(strings.ToLower(tmp) + secret))
  47. sign := query.Get("sign")
  48. if hex.EncodeToString(mh[:]) != sign {
  49. mh1 := md5.Sum([]byte(tmp + secret))
  50. if hex.EncodeToString(mh1[:]) != sign {
  51. err = ecode.SignCheckErr
  52. }
  53. }
  54. res = app
  55. return
  56. }
  57. // encodeQuery encodes the values into ``URL encoded'' form ("bar=baz&foo=quux") sorted by key.
  58. // NOTE: sign ignored!!!
  59. func encodeQuery(v url.Values) string {
  60. if v == nil {
  61. return ""
  62. }
  63. var buf bytes.Buffer
  64. keys := make([]string, 0, len(v))
  65. for k := range v {
  66. keys = append(keys, k)
  67. }
  68. sort.Strings(keys)
  69. for _, k := range keys {
  70. if k == "sign" {
  71. continue
  72. }
  73. vs := v[k]
  74. prefix := url.QueryEscape(k) + "="
  75. for _, v := range vs {
  76. if buf.Len() > 0 {
  77. buf.WriteByte('&')
  78. }
  79. buf.WriteString(prefix)
  80. buf.WriteString(url.QueryEscape(v))
  81. }
  82. }
  83. return buf.String()
  84. }