Skip to content

Commit

Permalink
Leverage the management client to make api requests in api cmd (#681)
Browse files Browse the repository at this point in the history
  • Loading branch information
sergiught authored Mar 17, 2023
1 parent 200ea69 commit 054145b
Show file tree
Hide file tree
Showing 5 changed files with 76 additions and 19 deletions.
3 changes: 3 additions & 0 deletions internal/auth0/auth0.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ type API struct {
Tenant TenantAPI
User UserAPI
Jobs JobsAPI

HTTPClient HTTPClientAPI
}

func NewAPI(m *management.Management) *API {
Expand All @@ -50,6 +52,7 @@ func NewAPI(m *management.Management) *API {
Tenant: m.Tenant,
User: m.User,
Jobs: m.Job,
HTTPClient: m,
}
}

Expand Down
17 changes: 17 additions & 0 deletions internal/auth0/http_client.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package auth0

import (
"net/http"

"github.com/auth0/go-auth0/management"
)

type HTTPClientAPI interface {
// NewRequest returns a new HTTP request.
// If the payload is not nil it will be encoded as JSON.
NewRequest(method, uri string, payload interface{}, options ...management.RequestOption) (*http.Request, error)

// Do triggers an HTTP request and returns an HTTP response,
// handling any context cancellations or timeouts.
Do(req *http.Request) (*http.Response, error)
}
29 changes: 14 additions & 15 deletions internal/cli/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@ import (
"net/url"
"strings"

"github.com/auth0/go-auth0/management"
"github.com/spf13/cobra"

"github.com/auth0/auth0-cli/internal/ansi"
"github.com/auth0/auth0-cli/internal/buildinfo"
"github.com/auth0/auth0-cli/internal/display"
"github.com/auth0/auth0-cli/internal/iostream"
"github.com/auth0/auth0-cli/internal/prompt"
Expand Down Expand Up @@ -62,7 +62,7 @@ type (
RawQueryParams map[string]string
Method string
URL *url.URL
Data io.Reader
Data interface{}
}
)

Expand Down Expand Up @@ -131,26 +131,25 @@ func apiCmdRun(cli *cli, inputs *apiCmdInputs) func(cmd *cobra.Command, args []s

var response *http.Response
if err := ansi.Waiting(func() error {
request, err := http.NewRequestWithContext(
cmd.Context(),
request, err := cli.api.HTTPClient.NewRequest(
inputs.Method,
inputs.URL.String(),
inputs.Data,
management.Context(cmd.Context()),
)
if err != nil {
return err
}

accessToken := getAccessToken(cli.config.Tenants[cli.tenant])
request.Header.Set("Authorization", fmt.Sprintf("Bearer %s", accessToken))
request.Header.Set("Content-Type", "application/json")
request.Header.Set("User-Agent", fmt.Sprintf("%s/%s", userAgent, strings.TrimPrefix(buildinfo.Version, "v")))

if cli.debug {
cli.renderer.Infof("[%s]: %s", request.Method, request.URL.String())
cli.renderer.Infof("Sending the following request: %+v", map[string]interface{}{
"method": request.Method,
"url": request.URL.String(),
"payload": inputs.Data,
})
}

response, err = http.DefaultClient.Do(request)
response, err = cli.api.HTTPClient.Do(request)
return err
}); err != nil {
return fmt.Errorf("failed to send request: %w", err)
Expand Down Expand Up @@ -232,12 +231,12 @@ func (i *apiCmdInputs) validateAndSetData() error {
)
}

if len(data) > 0 && !json.Valid(data) {
return fmt.Errorf("invalid json data given: %s", data)
if len(data) > 0 {
if err := json.Unmarshal(data, &i.Data); err != nil {
return fmt.Errorf("invalid json data given: %w", err)
}
}

i.Data = bytes.NewReader(data)

return nil
}

Expand Down
2 changes: 1 addition & 1 deletion internal/cli/api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ func TestAPICmdInputs_FromArgs(t *testing.T) {
name: "it fails to parse input arguments when data is not a valid JSON",
givenArgs: []string{"patch", "clients"},
givenDataFlag: "{",
expectedError: "invalid json data given: {",
expectedError: "invalid json data given: unexpected end of JSON input",
},
{
name: "it fails to parse input arguments when uri is invalid",
Expand Down
44 changes: 41 additions & 3 deletions test/integration/api-test-cases.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -9,23 +9,61 @@ tests:
contains:
- "idle_session_lifetime"

002 - it successfully uses the api command to patch tenant settings with piped data:
002 - it defaults to using a get method when method is missing:
command: auth0 api "tenants/settings" --query "include_fields=true" --query "fields=idle_session_lifetime"
exit-code: 0
stdout:
contains:
- "idle_session_lifetime"

003 - it successfully uses the api command to patch tenant settings with piped data:
command: cat ./test/integration/fixtures/update-tenant-settings.json | auth0 api patch "tenants/settings" && auth0 api get "tenants/settings" --query "include_fields=true" --query "fields=idle_session_lifetime"
exit-code: 0
stdout:
json:
idle_session_lifetime: "73"

003 - it successfully uses the api command to patch tenant settings:
004 - it successfully uses the api command to patch tenant settings:
command: auth0 api patch "tenants/settings" --data "{\"idle_session_lifetime\":72}" && auth0 api get "tenants/settings" --query "include_fields=true" --query "fields=idle_session_lifetime"
exit-code: 0
stdout:
json:
idle_session_lifetime: "72"

004 - it fails to use the api command to patch tenant settings with invalid json:
005 - it defaults to using a post method when method is missing but data flag is present:
command: auth0 api "clients" --data '{"name":"integration-test-app-for-api-cmd"}'
exit-code: 0
stdout:
json:
name: "integration-test-app-for-api-cmd"

006 - it fails to use the api command to patch tenant settings with invalid json:
command: auth0 api patch "tenants/settings" --data "{\"idle_session_lifetime:72}"
exit-code: 1
stderr:
contains:
- "failed to parse command inputs: invalid json data given"

007 - it fails to use the api command if an invalid method is given:
command: auth0 api conquer "tenants/settings"
exit-code: 1
stderr:
contains:
- "failed to parse command inputs: invalid method given"

008 - it throws a warning when both piped data and the data flag are present:
command: cat ./test/integration/fixtures/update-tenant-settings.json | auth0 api patch "tenants/settings" --data "{\"idle_session_lifetime\":72}"
exit-code: 0
stdout:
json:
idle_session_lifetime: "72"
stderr:
contains:
- "JSON data was passed using both the flag and as piped input. The Auth0 CLI will use only the data from the flag."

009 - it successfully prints out debug log messages:
command: auth0 api get "stats/daily" --query "from=20000317" --query "to=20000317" --debug
exit-code: 0
stderr:
contains:
- "Sending the following request"

0 comments on commit 054145b

Please sign in to comment.