| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172 |
- 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()
- }
- }
|