github.com/kyma-incubator/compass/components/director@v0.0.0-20230623144113-d764f56ff805/pkg/http/request.go (about) 1 package http 2 3 import ( 4 "context" 5 "net/http" 6 7 "github.com/kyma-incubator/compass/components/director/internal/model" 8 9 "github.com/kyma-incubator/compass/components/director/pkg/apperrors" 10 11 "golang.org/x/oauth2" 12 "golang.org/x/oauth2/clientcredentials" 13 ) 14 15 const tenantHeader = "Tenant" 16 17 // GetRequestWithCredentials executes a GET http request to the given url with the provided auth credentials 18 func GetRequestWithCredentials(ctx context.Context, client *http.Client, url, tnt string, auth *model.Auth) (*http.Response, error) { 19 if auth == nil || (auth.Credential.Basic == nil && auth.Credential.Oauth == nil) { 20 return nil, apperrors.NewInvalidDataError("Credentials not provided") 21 } 22 23 req, err := http.NewRequest(http.MethodGet, url, nil) 24 if err != nil { 25 return nil, err 26 } 27 28 if len(tnt) > 0 { 29 req.Header.Set(tenantHeader, tnt) 30 } 31 32 var resp *http.Response 33 if auth.Credential.Basic != nil { 34 req.SetBasicAuth(auth.Credential.Basic.Username, auth.Credential.Basic.Password) 35 36 resp, err = client.Do(req) 37 38 if err == nil && resp.StatusCode == http.StatusOK { 39 return resp, nil 40 } 41 } 42 43 if auth.Credential.Oauth != nil { 44 resp, err = secureClient(ctx, client, auth).Do(req) 45 } 46 47 return resp, err 48 } 49 50 func secureClient(ctx context.Context, client *http.Client, auth *model.Auth) *http.Client { 51 conf := &clientcredentials.Config{ 52 ClientID: auth.Credential.Oauth.ClientID, 53 ClientSecret: auth.Credential.Oauth.ClientSecret, 54 TokenURL: auth.Credential.Oauth.URL, 55 } 56 57 ctx = context.WithValue(ctx, oauth2.HTTPClient, client) 58 securedClient := conf.Client(ctx) 59 securedClient.Timeout = client.Timeout 60 return securedClient 61 } 62 63 // GetRequestWithoutCredentials executes a GET http request to the given url 64 func GetRequestWithoutCredentials(client *http.Client, url, tnt string) (*http.Response, error) { 65 req, err := http.NewRequest(http.MethodGet, url, nil) 66 if err != nil { 67 return nil, err 68 } 69 70 if len(tnt) > 0 { 71 req.Header.Set(tenantHeader, tnt) 72 } 73 74 return client.Do(req) 75 }