63 lines
1.6 KiB
Go
63 lines
1.6 KiB
Go
package middleware
|
|
|
|
import (
|
|
"crypto/md5"
|
|
"encoding/hex"
|
|
"fmt"
|
|
"github.com/cloudwego/hertz/pkg/app"
|
|
"github.com/cloudwego/hertz/pkg/protocol/consts"
|
|
"weather_and_earthquake/internal/config"
|
|
)
|
|
import "context"
|
|
|
|
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) {
|
|
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)
|
|
}
|
|
}
|