55 lines
1.3 KiB
Go
55 lines
1.3 KiB
Go
|
package middleware
|
||
|
|
||
|
import (
|
||
|
"bytes"
|
||
|
"encoding/json"
|
||
|
"io"
|
||
|
"net/http"
|
||
|
"rs/cmd/api/internal/config"
|
||
|
"rs/untils/response"
|
||
|
"rs/untils/sign"
|
||
|
)
|
||
|
|
||
|
type SignMiddleware struct {
|
||
|
c *config.Config
|
||
|
}
|
||
|
|
||
|
func NewSignMiddleware(c *config.Config) *SignMiddleware {
|
||
|
return &SignMiddleware{
|
||
|
c: c,
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func (m *SignMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
|
||
|
return func(w http.ResponseWriter, r *http.Request) {
|
||
|
var (
|
||
|
reqDataMap map[string]interface{}
|
||
|
)
|
||
|
|
||
|
originalBody, err := io.ReadAll(r.Body)
|
||
|
reqData := make([]byte, len(originalBody))
|
||
|
copy(reqData, originalBody)
|
||
|
r.Body = io.NopCloser(bytes.NewReader(originalBody))
|
||
|
if err != nil {
|
||
|
response.Err(w, response.HTTP_AUTH_FAIL, "获取请求参数失败")
|
||
|
}
|
||
|
err = json.Unmarshal(reqData, &reqDataMap)
|
||
|
if err != nil {
|
||
|
response.Err(w, response.HTTP_AUTH_FAIL, "获取请求参数失败")
|
||
|
}
|
||
|
if _, ok := reqDataMap["sign"]; !ok {
|
||
|
response.Err(w, response.HTTP_AUTH_FAIL, "未找到签名字段")
|
||
|
}
|
||
|
if _, ok := reqDataMap["sign"]; !ok {
|
||
|
response.Err(w, response.HTTP_AUTH_FAIL, err.Error())
|
||
|
}
|
||
|
signString := reqDataMap["sign"].(string)
|
||
|
sysSign, err := sign.GetSign(reqDataMap, m.c.Sys.Key)
|
||
|
if sysSign != signString {
|
||
|
response.Err(w, response.HTTP_AUTH_FAIL, "签名不正确")
|
||
|
return
|
||
|
}
|
||
|
next(w, r)
|
||
|
}
|
||
|
}
|