key.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package middleware
  2. import (
  3. "crypto/hmac"
  4. "crypto/sha256"
  5. "encoding/hex"
  6. "fmt"
  7. "mtp2_if/config"
  8. "mtp2_if/global/e"
  9. "net/http"
  10. "runtime"
  11. "github.com/gin-gonic/gin"
  12. )
  13. func CheckKey() gin.HandlerFunc {
  14. return func(c *gin.Context) {
  15. if !config.SerCfg.GetApiKeyMode() {
  16. c.Next()
  17. return
  18. }
  19. // windows下方便开发调试, 不做校验
  20. if config.SerCfg.GetDebugMode() &&
  21. runtime.GOOS == "windows" {
  22. c.Next()
  23. return
  24. }
  25. timestamp := c.GetHeader("Timestamp")
  26. token := c.GetHeader("Authorization")
  27. verification := c.GetHeader("Verification")
  28. if timestamp == "" || token == "" || verification == "" {
  29. c.JSON(http.StatusUnauthorized, gin.H{
  30. "code": e.ERROR,
  31. "msg": "缺少检验参数",
  32. "data": struct{}{},
  33. })
  34. c.Abort()
  35. return
  36. }
  37. s := fmt.Sprintf("%s%s", token, timestamp)
  38. hashed := hmac.New(sha256.New, []byte(config.SerCfg.WebCfg.ApiKey))
  39. hashed.Write([]byte(s))
  40. h := hex.EncodeToString(hashed.Sum(nil))
  41. if h == "" {
  42. c.JSON(http.StatusUnauthorized, gin.H{
  43. "code": e.ERROR,
  44. "msg": "接口检验失败",
  45. "data": struct{}{},
  46. })
  47. c.Abort()
  48. return
  49. }
  50. if h != verification {
  51. c.JSON(http.StatusUnauthorized, gin.H{
  52. "code": e.ERROR,
  53. "msg": "非法调用接口",
  54. "data": struct{}{},
  55. })
  56. c.Abort()
  57. return
  58. }
  59. // 检验成功
  60. c.Next()
  61. }
  62. }