sign.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package middware
  2. import (
  3. "adm-data-gateway/errors"
  4. "crypto/md5"
  5. "encoding/hex"
  6. "net/http"
  7. "github.com/gin-gonic/gin"
  8. "google.golang.org/grpc/status"
  9. )
  10. func Sign() gin.HandlerFunc {
  11. return func(ctx *gin.Context) {
  12. appKey := ctx.GetHeader("appkey")
  13. s := status.New(10001, "内部服务错误")
  14. if appKey == "" {
  15. if v, ok := status.FromError(errors.AppKeyNotExistError); ok {
  16. s = v
  17. }
  18. ctx.JSON(http.StatusOK, Response{s.Code(), s.Message()})
  19. ctx.Abort()
  20. return
  21. }
  22. sign := ctx.GetHeader("sign")
  23. if sign == "" {
  24. if v, ok := status.FromError(errors.SignNotExistError); ok {
  25. s = v
  26. }
  27. ctx.JSON(http.StatusOK, Response{s.Code(), s.Message()})
  28. ctx.Abort()
  29. return
  30. }
  31. ts := ctx.GetHeader("ts")
  32. if ts == "" {
  33. if v, ok := status.FromError(errors.TimeStampNotExistError); ok {
  34. s = v
  35. }
  36. ctx.JSON(http.StatusOK, Response{s.Code(), s.Message()})
  37. ctx.Abort()
  38. return
  39. }
  40. h := md5.New()
  41. h.Write([]byte(appKey + ts))
  42. if sign != hex.EncodeToString(h.Sum(nil)) {
  43. if v, ok := status.FromError(errors.SignNotCorrectError); ok {
  44. s = v
  45. }
  46. ctx.JSON(http.StatusOK, Response{s.Code(), s.Message()})
  47. ctx.Abort()
  48. return
  49. }
  50. ctx.Next()
  51. }
  52. }