com.snow.auto_monitor/app/http/middlewares/sign_verify.go

93 lines
2.0 KiB
Go
Raw Normal View History

2024-07-12 18:11:21 +08:00
package middlewares
import (
"crypto/md5"
"encoding/hex"
"encoding/json"
"fmt"
"sort"
"strings"
common "com.snow.auto_monitor/app/http/controllers"
mermod "com.snow.auto_monitor/app/models/merchant"
"github.com/gin-gonic/gin"
"github.com/qit-team/snow-core/log/logger"
)
type Verify struct {
MerchantId int64 `json:"merchant_id" validate:"required"`
TimeStamp int64 `json:"time_stamp" validate:"required"`
Sign string `json:"sign" validate:"required"`
}
func getMD5Hash(input string) string {
hash := md5.Sum([]byte(input))
return hex.EncodeToString(hash[:])
}
func GenMD5Sign(data map[string]interface{}, secretKey string) string {
keys := make([]string, 0, len(data))
for key := range data {
if key != "sign" && key != "Sign" {
keys = append(keys, key)
}
}
sort.Strings(keys)
rawStr := ""
for _, key := range keys {
value := fmt.Sprintf("%v", data[key])
if rawStr != "" {
rawStr += "&"
}
rawStr += fmt.Sprintf("%s=%s", key, value)
}
rawStr += "&key=" + secretKey
sign := strings.ToUpper(getMD5Hash(rawStr))
return sign
}
func VerifySign() gin.HandlerFunc {
return func(c *gin.Context) {
var data map[string]interface{}
body, err := common.ReadBody(c)
if err != nil {
common.Error(c, 400, err.Error())
c.Abort()
return
}
err = json.Unmarshal(body, &data)
if err != nil {
common.Error(c, 400, err.Error())
c.Abort()
return
}
if data["merchant_id"] == nil || data["time_stamp"] == nil || data["sign"] == nil {
common.Error(c, 400, "参数错误")
c.Abort()
return
}
//验证商户是否存在
merchanId := int64(data["merchant_id"].(float64))
merchant, has, err := mermod.GetInstance().GetById(merchanId)
if err != nil {
common.Error500(c)
c.Abort()
return
}
if !has {
common.Error(c, 400, "商户不存在")
c.Abort()
return
}
//验证签名是否正确
2024-07-15 15:45:09 +08:00
hash := GenMD5Sign(data, merchant.PrivateKey)
2024-07-12 18:11:21 +08:00
logger.Info(c, "Sign", hash)
if hash != data["sign"] {
common.Error(c, 400, "签名错误")
c.Abort()
return
}
}
}