github.com/free5gc/openapi@v1.0.8/oauth/get_token_context.go (about) 1 package oauth 2 3 import ( 4 "context" 5 "sync" 6 "time" 7 8 "github.com/antihax/optional" 9 "golang.org/x/oauth2" 10 11 "github.com/free5gc/openapi" 12 "github.com/free5gc/openapi/Nnrf_AccessToken" 13 "github.com/free5gc/openapi/models" 14 ) 15 16 var tokenMap sync.Map 17 var clientMap sync.Map 18 19 func GetTokenCtx( 20 nfType, targetNF models.NfType, 21 nfId, nrfUri, scope string, 22 ) (context.Context, *models.ProblemDetails, error) { 23 tok, pd, err := sendAccTokenReq(nfType, targetNF, nfId, nrfUri, scope) 24 if err != nil { 25 return nil, pd, err 26 } 27 return context.WithValue(context.Background(), 28 openapi.ContextOAuth2, tok), pd, nil 29 } 30 31 func sendAccTokenReq( 32 nfType, targetNF models.NfType, 33 nfId, nrfUri, scope string, 34 ) (oauth2.TokenSource, *models.ProblemDetails, error) { 35 var client *Nnrf_AccessToken.APIClient 36 37 configuration := Nnrf_AccessToken.NewConfiguration() 38 configuration.SetBasePath(nrfUri) 39 40 if val, ok := clientMap.Load(configuration); ok { 41 client = val.(*Nnrf_AccessToken.APIClient) 42 } else { 43 client = Nnrf_AccessToken.NewAPIClient(configuration) 44 clientMap.Store(configuration, client) 45 } 46 47 var tok models.AccessTokenRsp 48 if val, ok := tokenMap.Load(scope); ok { 49 tok = val.(models.AccessTokenRsp) 50 if int32(time.Now().Unix()) < tok.ExpiresIn { 51 token := &oauth2.Token{ 52 AccessToken: tok.AccessToken, 53 TokenType: tok.TokenType, 54 Expiry: time.Unix(int64(tok.ExpiresIn), 0), 55 } 56 return oauth2.StaticTokenSource(token), nil, nil 57 } 58 } 59 tok, res, err := client.AccessTokenRequestApi.AccessTokenRequest( 60 context.Background(), "client_credentials", 61 nfId, scope, &Nnrf_AccessToken.AccessTokenRequestParamOpts{ 62 NfType: optional.NewInterface(nfType), 63 TargetNfType: optional.NewInterface(targetNF), 64 }) 65 66 if err == nil { 67 tokenMap.Store(scope, tok) 68 token := &oauth2.Token{ 69 AccessToken: tok.AccessToken, 70 TokenType: tok.TokenType, 71 Expiry: time.Unix(int64(tok.ExpiresIn), 0), 72 } 73 return oauth2.StaticTokenSource(token), nil, nil 74 } else if res != nil { 75 if res.Status != err.Error() { 76 return nil, nil, err 77 } 78 accesstoken_err := err.(openapi.GenericOpenAPIError).Model().(models.AccessTokenErr) 79 pd := &models.ProblemDetails{ 80 AccessTokenError: &accesstoken_err, 81 } 82 return nil, pd, err 83 } else { 84 return nil, nil, openapi.ReportError("server no response") 85 } 86 }