79 lines
1.7 KiB
Go
79 lines
1.7 KiB
Go
package http_gateway
|
||
|
||
import (
|
||
"fmt"
|
||
"git.hlsq.asia/mmorpg/service-common/net/http/http_resp"
|
||
"git.hlsq.asia/mmorpg/service-common/utils"
|
||
"git.hlsq.asia/mmorpg/service-gateway/config"
|
||
"git.hlsq.asia/mmorpg/service-gateway/internal/global"
|
||
"github.com/gin-contrib/cors"
|
||
"github.com/gin-gonic/gin"
|
||
"go.uber.org/zap"
|
||
"strings"
|
||
"time"
|
||
)
|
||
|
||
func corsConfig() cors.Config {
|
||
return cors.Config{
|
||
AllowMethods: []string{"GET", "POST", "OPTIONS"},
|
||
AllowHeaders: []string{"Content-Type", "Authorization"},
|
||
AllowCredentials: false,
|
||
AllowAllOrigins: true,
|
||
MaxAge: 12 * time.Hour,
|
||
}
|
||
}
|
||
|
||
func ginLogger(logger *zap.SugaredLogger) gin.HandlerFunc {
|
||
return func(c *gin.Context) {
|
||
start := time.Now()
|
||
path := c.Request.URL.Path
|
||
c.Next()
|
||
cost := time.Since(start)
|
||
|
||
logger.Infof(fmt.Sprintf(
|
||
"HTTP Method:%v Code:%v Time:%v IP:%v Path:%v",
|
||
c.Request.Method,
|
||
c.Writer.Status(),
|
||
cost,
|
||
c.ClientIP(),
|
||
path),
|
||
)
|
||
}
|
||
}
|
||
|
||
func authJwt() gin.HandlerFunc {
|
||
return func(c *gin.Context) {
|
||
// 如果是Public接口,有Token就读,没有就算了
|
||
public := false
|
||
for _, path := range global.PublicPaths {
|
||
if strings.HasPrefix(c.Request.URL.Path, path) {
|
||
public = true
|
||
break
|
||
}
|
||
}
|
||
|
||
token := strings.TrimPrefix(c.GetHeader("Authorization"), "Bearer ")
|
||
if token == "" {
|
||
if public {
|
||
c.Next()
|
||
return
|
||
}
|
||
http_resp.AbortUnauthorized(c)
|
||
return
|
||
}
|
||
claims, err := utils.ParseToken(token, config.Get().Auth.Secret)
|
||
if err != nil {
|
||
if public {
|
||
c.Next()
|
||
return
|
||
}
|
||
http_resp.AbortUnauthorized(c)
|
||
return
|
||
}
|
||
|
||
// 这里将Header写到请求中,grpc-gateway框架会读取然后传给grpc服务
|
||
c.Request.Header.Set("X-Usn", claims.USN)
|
||
c.Next()
|
||
}
|
||
}
|