WEQServer/internal/middleware/middleware.go

63 lines
1.6 KiB
Go
Raw Normal View History

package middleware
2025-10-31 10:01:06 +00:00
import (
2025-11-03 11:12:39 +00:00
"crypto/md5"
"encoding/hex"
"fmt"
2025-10-31 10:01:06 +00:00
"github.com/cloudwego/hertz/pkg/app"
2025-11-03 11:12:39 +00:00
"github.com/cloudwego/hertz/pkg/protocol/consts"
2025-10-31 10:01:06 +00:00
"weather_and_earthquake/internal/config"
)
import "context"
2025-10-31 10:01:06 +00:00
var Apps *config.Apps
// 跨域
func CorsMiddleware() app.HandlerFunc {
return func(ctx context.Context, c *app.RequestContext) {
c.Response.Header.Set("Access-Control-Allow-Origin", "*")
c.Response.Header.Set("Access-Control-Allow-Methods", "*")
c.Response.Header.Set("Access-Control-Allow-Headers", "*")
c.Response.Header.Set("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Cache-Control, Content-Language, Content-Type")
c.Next(ctx)
}
}
// 校验签名
func AuthMiddleware() app.HandlerFunc {
return func(ctx context.Context, c *app.RequestContext) {
2025-11-03 11:12:39 +00:00
author := c.Request.Header.Get("Authorization")
timestamp := c.Request.Header.Get("Timestamp")
sign := c.Request.Header.Get("Sign")
if author == "" || timestamp == "" || sign == "" {
c.AbortWithMsg("Missing Parameter.", consts.StatusUnauthorized)
return
}
var secret string = ""
for _, v := range Apps.AppSecrets {
if v.Id == author {
secret = v.Secret
break
}
}
if len(secret) == 0 {
c.AbortWithMsg("Wrong Authorization.", consts.StatusUnauthorized)
return
}
temp := fmt.Sprintf("%s-%s-%s", author, timestamp, secret)
h := md5.New()
h.Write([]byte(temp))
localSign := hex.EncodeToString(h.Sum(nil))
if localSign != sign {
c.AbortWithMsg("Wrong Signature.", consts.StatusUnauthorized)
return
}
c.Next(ctx)
}
}