package middleware import ( "crypto/hmac" "crypto/sha256" "encoding/hex" "fmt" "mtp2_if/config" "mtp2_if/global/e" "net/http" "runtime" "github.com/gin-gonic/gin" ) func CheckKey() gin.HandlerFunc { return func(c *gin.Context) { if !config.SerCfg.GetApiKeyMode() { c.Next() return } // windows下方便开发调试, 不做校验 if config.SerCfg.GetDebugMode() && runtime.GOOS == "windows" { c.Next() return } timestamp := c.GetHeader("Timestamp") token := c.GetHeader("Authorization") verification := c.GetHeader("Verification") if timestamp == "" || token == "" || verification == "" { c.JSON(http.StatusUnauthorized, gin.H{ "code": e.ERROR, "msg": "缺少检验参数", "data": struct{}{}, }) c.Abort() return } s := fmt.Sprintf("%s%s", token, timestamp) hashed := hmac.New(sha256.New, []byte(config.SerCfg.WebCfg.ApiKey)) hashed.Write([]byte(s)) h := hex.EncodeToString(hashed.Sum(nil)) if h == "" { c.JSON(http.StatusUnauthorized, gin.H{ "code": e.ERROR, "msg": "接口检验失败", "data": struct{}{}, }) c.Abort() return } if h != verification { c.JSON(http.StatusUnauthorized, gin.H{ "code": e.ERROR, "msg": "非法调用接口", "data": struct{}{}, }) c.Abort() return } // 检验成功 c.Next() } }