56 lines
1.3 KiB
Go
56 lines
1.3 KiB
Go
package activityauth
|
|
|
|
import (
|
|
"bytes"
|
|
"crypto/hmac"
|
|
"crypto/sha256"
|
|
"encoding/base64"
|
|
"encoding/hex"
|
|
"io"
|
|
"net/http"
|
|
|
|
"91porn-server/app/appg"
|
|
"91porn-server/common/log"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
// HmacAuth 活动服回调 HMAC-SHA256 签名校验中间件
|
|
func HmacAuth(c *gin.Context) {
|
|
signature := c.GetHeader("X-Signature")
|
|
if signature == "" {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"code": 401, "msg": "missing signature"})
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
bodyBytes, err := io.ReadAll(c.Request.Body)
|
|
if err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"code": 400, "msg": "read body failed"})
|
|
c.Abort()
|
|
return
|
|
}
|
|
c.Request.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))
|
|
|
|
secretKey := appg.Conf.ActivityServer.SecretKey
|
|
keyBytes, err := base64.StdEncoding.DecodeString(secretKey)
|
|
if err != nil {
|
|
log.Error("activityauth: decode secretKey failed", log.E(err))
|
|
c.JSON(http.StatusInternalServerError, gin.H{"code": 500, "msg": "server config error"})
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
h := hmac.New(sha256.New, keyBytes)
|
|
h.Write(bodyBytes)
|
|
expected := hex.EncodeToString(h.Sum(nil))
|
|
|
|
if !hmac.Equal([]byte(expected), []byte(signature)) {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"code": 401, "msg": "invalid signature"})
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
c.Next()
|
|
}
|