rag/internal/providers/gin_middleware.go

75 lines
1.9 KiB
Go
Raw Normal View History

2024-06-13 08:36:10 +00:00
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 类型。")
2024-06-15 16:45:32 +00:00
ErrEmptyResponse = errors.New("我们的服务器返回了空请求,可能某些环节出了问题。")
2024-06-13 08:36:10 +00:00
)
const AnonymousUser = "anonymous"
2024-06-15 16:45:32 +00:00
// DIJWTAuth 用于注入到方法签名中。我觉得下面的代码以后可以优化。
func DIJWTAuth(c *gin.Context) *consts.User {
2024-06-13 08:36:10 +00:00
var sub = AnonymousUser
2024-06-15 16:45:32 +00:00
var jwtIdToken = &consts.User{}
2024-06-13 08:36:10 +00:00
if Config.DebugMode.Enable {
2024-06-15 16:45:32 +00:00
jwtIdToken.Token.Sub = sub
2024-06-13 08:36:10 +00:00
} else {
// get authorization header
authorization := c.Request.Header.Get("Authorization")
if authorization == "" {
helper.ResponseError(c, http.StatusUnauthorized, ErrJWTFormatError)
2024-06-15 16:45:32 +00:00
return nil
2024-06-13 08:36:10 +00:00
}
authSplit := strings.Split(authorization, " ")
if len(authSplit) != 2 {
helper.ResponseError(c, http.StatusUnauthorized, ErrJWTFormatError)
2024-06-15 16:45:32 +00:00
return nil
2024-06-13 08:36:10 +00:00
}
if authSplit[0] != "Bearer" {
helper.ResponseError(c, http.StatusUnauthorized, ErrNotBearerType)
2024-06-15 16:45:32 +00:00
return nil
2024-06-13 08:36:10 +00:00
}
token, err := ParseJWT(authSplit[1])
if err != nil {
helper.ResponseError(c, http.StatusUnauthorized, ErrJWTFormatError)
2024-06-15 16:45:32 +00:00
return nil
2024-06-13 08:36:10 +00:00
}
sub, err = token.Claims.GetSubject()
if err != nil {
helper.ResponseError(c, http.StatusUnauthorized, ErrNotValidToken)
2024-06-15 16:45:32 +00:00
return nil
2024-06-13 08:36:10 +00:00
}
2024-06-15 16:45:32 +00:00
err = mapstructure.Decode(token.Claims, &jwtIdToken.Token)
2024-06-13 08:36:10 +00:00
if err != nil {
Logger.Error("Failed to map token claims to JwtIDToken struct.\nError: " + err.Error())
helper.ResponseError(c, http.StatusUnauthorized, ErrNotValidToken)
2024-06-15 16:45:32 +00:00
return nil
2024-06-13 08:36:10 +00:00
}
}
2024-06-15 16:45:32 +00:00
return jwtIdToken
2024-06-13 08:36:10 +00:00
}
func MiddlewareJSONResponse(c *gin.Context) {
c.Header("Content-Type", "application/json; charset=utf-8")
c.Next()
}