78 lines
1.8 KiB
Go
78 lines
1.8 KiB
Go
|
package providers
|
||
|
|
||
|
import (
|
||
|
"errors"
|
||
|
"fmt"
|
||
|
"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 类型。")
|
||
|
)
|
||
|
|
||
|
const AnonymousUser = "anonymous"
|
||
|
|
||
|
func MiddlewareJWTAuth(c *gin.Context) {
|
||
|
var sub = AnonymousUser
|
||
|
var jwtIdToken = consts.UserTokenInfo{}
|
||
|
|
||
|
if Config.DebugMode.Enable {
|
||
|
jwtIdToken.Sub = sub
|
||
|
} else {
|
||
|
// get authorization header
|
||
|
authorization := c.Request.Header.Get("Authorization")
|
||
|
|
||
|
if authorization == "" {
|
||
|
helper.ResponseError(c, http.StatusUnauthorized, ErrJWTFormatError)
|
||
|
return
|
||
|
}
|
||
|
|
||
|
authSplit := strings.Split(authorization, " ")
|
||
|
if len(authSplit) != 2 {
|
||
|
helper.ResponseError(c, http.StatusUnauthorized, ErrJWTFormatError)
|
||
|
return
|
||
|
}
|
||
|
|
||
|
if authSplit[0] != "Bearer" {
|
||
|
helper.ResponseError(c, http.StatusUnauthorized, ErrNotBearerType)
|
||
|
return
|
||
|
}
|
||
|
|
||
|
token, err := ParseJWT(authSplit[1])
|
||
|
if err != nil {
|
||
|
helper.ResponseError(c, http.StatusUnauthorized, ErrJWTFormatError)
|
||
|
return
|
||
|
}
|
||
|
sub, err = token.Claims.GetSubject()
|
||
|
if err != nil {
|
||
|
helper.ResponseError(c, http.StatusUnauthorized, ErrNotValidToken)
|
||
|
return
|
||
|
}
|
||
|
|
||
|
err = mapstructure.Decode(token.Claims, &jwtIdToken)
|
||
|
if err != nil {
|
||
|
Logger.Error("Failed to map token claims to JwtIDToken struct.\nError: " + err.Error())
|
||
|
helper.ResponseError(c, http.StatusUnauthorized, ErrNotValidToken)
|
||
|
return
|
||
|
}
|
||
|
|
||
|
fmt.Println("test", jwtIdToken.Sub)
|
||
|
}
|
||
|
|
||
|
c.Set(consts.UserTokenInfoKey, jwtIdToken)
|
||
|
|
||
|
return
|
||
|
}
|
||
|
|
||
|
func MiddlewareJSONResponse(c *gin.Context) {
|
||
|
c.Header("Content-Type", "application/json; charset=utf-8")
|
||
|
c.Next()
|
||
|
}
|