rag/internal/providers/jwks.go

63 lines
1.1 KiB
Go
Raw Normal View History

2024-06-13 01:16:48 +00:00
package providers
import (
"context"
"errors"
2024-06-13 07:36:51 +00:00
"framework_v2/internal/consts"
2024-06-13 01:16:48 +00:00
"github.com/MicahParks/keyfunc/v3"
"github.com/golang-jwt/jwt/v5"
"time"
)
var refreshRate = 1 * time.Hour
var Jwks keyfunc.Keyfunc
var (
ErrJWKSNotInitialized = errors.New("JWKS is not initialized")
)
func InitJwksRefresh() {
// 启动一个定时器
go func() {
for {
RefreshJWKS()
time.Sleep(refreshRate)
}
}()
}
func RefreshJWKS() {
Logger.Info("Refreshing JWKS...")
var err error
Jwks, err = keyfunc.NewDefault([]string{Config.JWKS.Url})
if err != nil {
Logger.Error("Failed to create JWK Set from resource at the given URL.\nError: " + err.Error())
}
Logger.Info("JWKS refreshed.")
}
func ParseJWT(jwtB64 string) (*jwt.Token, error) {
//if Jwks.Keyfunc == nil {
// Logger.Error(ErrJWKSNotInitialized.Error())
// return nil, ErrJWKSNotInitialized
//}
token, err := jwt.Parse(jwtB64, Jwks.Keyfunc)
return token, err
}
2024-06-13 07:36:51 +00:00
func GetAuthFromCtx(ctx context.Context) *consts.UserTokenInfo {
2024-06-13 01:16:48 +00:00
auth := ctx.Value("auth")
if auth == nil {
return nil
}
2024-06-13 07:36:51 +00:00
return auth.(*consts.UserTokenInfo)
2024-06-13 01:16:48 +00:00
}