rag/internal/providers/gin_middleware.go
2024-06-16 00:45:32 +08:00

75 lines
1.9 KiB
Go

package providers
import (
"errors"
"framework_v2/internal/consts"
"framework_v2/internal/helper"
"github.com/gin-gonic/gin"
"github.com/mitchellh/mapstructure"
"net/http"
"strings"
)
var (
ErrNotValidToken = errors.New("无效的 JWT 令牌。")
ErrJWTFormatError = errors.New("JWT 格式错误。")
ErrNotBearerType = errors.New("不是 Bearer 类型。")
ErrEmptyResponse = errors.New("我们的服务器返回了空请求,可能某些环节出了问题。")
)
const AnonymousUser = "anonymous"
// DIJWTAuth 用于注入到方法签名中。我觉得下面的代码以后可以优化。
func DIJWTAuth(c *gin.Context) *consts.User {
var sub = AnonymousUser
var jwtIdToken = &consts.User{}
if Config.DebugMode.Enable {
jwtIdToken.Token.Sub = sub
} else {
// get authorization header
authorization := c.Request.Header.Get("Authorization")
if authorization == "" {
helper.ResponseError(c, http.StatusUnauthorized, ErrJWTFormatError)
return nil
}
authSplit := strings.Split(authorization, " ")
if len(authSplit) != 2 {
helper.ResponseError(c, http.StatusUnauthorized, ErrJWTFormatError)
return nil
}
if authSplit[0] != "Bearer" {
helper.ResponseError(c, http.StatusUnauthorized, ErrNotBearerType)
return nil
}
token, err := ParseJWT(authSplit[1])
if err != nil {
helper.ResponseError(c, http.StatusUnauthorized, ErrJWTFormatError)
return nil
}
sub, err = token.Claims.GetSubject()
if err != nil {
helper.ResponseError(c, http.StatusUnauthorized, ErrNotValidToken)
return nil
}
err = mapstructure.Decode(token.Claims, &jwtIdToken.Token)
if err != nil {
Logger.Error("Failed to map token claims to JwtIDToken struct.\nError: " + err.Error())
helper.ResponseError(c, http.StatusUnauthorized, ErrNotValidToken)
return nil
}
}
return jwtIdToken
}
func MiddlewareJSONResponse(c *gin.Context) {
c.Header("Content-Type", "application/json; charset=utf-8")
c.Next()
}