Skip to content

Commit

Permalink
Fix data source client to search by name through all available clients
Browse files Browse the repository at this point in the history
  • Loading branch information
sergiught committed Aug 26, 2022
1 parent f7abd37 commit f69fb28
Showing 1 changed file with 27 additions and 15 deletions.
42 changes: 27 additions & 15 deletions internal/provider/data_source_auth0_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package provider
import (
"context"

"github.com/auth0/go-auth0"
"github.com/auth0/go-auth0/management"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
Expand All @@ -30,29 +29,42 @@ func newClientSchema() map[string]*schema.Schema {
}

func readDataClient(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
clientID := auth0.StringValue(String(d, "client_id"))
clientID := d.Get("client_id").(string)
if clientID != "" {
d.SetId(clientID)
return readClient(ctx, d, m)
}

// If not provided ID, perform looking of client by name
name := auth0.StringValue(String(d, "name"))
name := d.Get("name").(string)
if name == "" {
return diag.Errorf("no 'client_id' or 'name' was specified")
return diag.Errorf("One of 'client_id' or 'name' is required.")
}

api := m.(*management.Management)
clients, err := api.Client.List(management.IncludeFields("client_id", "name"))
if err != nil {
return diag.FromErr(err)
}
for _, client := range clients.Clients {
if auth0.StringValue(client.Name) == name {
clientID = auth0.StringValue(client.ClientID)
d.SetId(clientID)
return readClient(ctx, d, m)

var page int
for {
clients, err := api.Client.List(
management.IncludeFields("client_id", "name"),
management.Page(page),
)
if err != nil {
return diag.FromErr(err)
}

for _, client := range clients.Clients {
if client.GetName() == name {
d.SetId(client.GetClientID())
return readClient(ctx, d, m)
}
}

if !clients.HasNext() {
break
}

page++
}
return diag.Errorf("no client found with 'name' = '%s'", name)

return diag.Errorf("No client found with \"name\" = %q", name)
}

0 comments on commit f69fb28

Please sign in to comment.