service/library/middleware/jwt_authenticator.go

41 lines
815 B
Go
Raw Normal View History

2023-12-21 22:17:40 +08:00
package middleware
import (
"fmt"
"service/api/base"
"service/library/logger"
"github.com/gin-gonic/gin"
)
var (
DefaultJwtAuthenticator gin.HandlerFunc
)
2024-08-07 22:22:32 +08:00
func InitJwtAuthenticator(verifyFunc func(*gin.Context, string) (int64, error)) {
2023-12-21 22:17:40 +08:00
DefaultJwtAuthenticator = func(ctx *gin.Context) {
//1.获取token
baseRequest, ok := ctx.MustGet("client_req").(base.BaseRequestAccessible)
if !ok {
base.CheckBadRequest(ctx, fmt.Errorf("BaseRequest acquire failed"))
return
}
tokenString := baseRequest.GetBaseRequest().Token
logger.Info("token : %v", tokenString)
//2.校验
2024-08-07 22:22:32 +08:00
id, err := verifyFunc(ctx, tokenString)
2023-12-21 22:17:40 +08:00
if !base.CheckBadRequest(ctx, err) {
return
}
2024-08-07 22:22:32 +08:00
ctx.Set("token_uuid", id)
2023-12-21 22:17:40 +08:00
ctx.Next()
}
}
func JwtAuthenticator() gin.HandlerFunc {
return DefaultJwtAuthenticator
}