Skip to content

Commit

Permalink
cli: write out new default org if the user cannot see the previous de…
Browse files Browse the repository at this point in the history
…fault
  • Loading branch information
nickvanw committed Jan 30, 2025
1 parent 6504920 commit d32a799
Showing 1 changed file with 39 additions and 10 deletions.
49 changes: 39 additions & 10 deletions internal/cmd/auth/login.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,11 @@ func LoginCmd(ch *cmdutil.Helper) *cobra.Command {
writeConfig = true
}

if !writeConfig && cfg.Organization != "" {
hasOrg, _ := hasOrg(ctx, cfg.Organization, accessToken, authURL)
writeConfig = !hasOrg
}

if writeConfig || cfg.Organization == "" {
err = writeDefaultOrganization(ctx, accessToken, authURL)
if err != nil {
Expand All @@ -98,20 +103,11 @@ func LoginCmd(ch *cmdutil.Helper) *cobra.Command {
}

func writeDefaultOrganization(ctx context.Context, accessToken, authURL string) error {
// After successfully logging in, attempt to set the org by default.
client, err := planetscale.NewClient(
planetscale.WithAccessToken(accessToken),
planetscale.WithBaseURL(authURL),
)
orgs, err := listCurrentOrgs(ctx, accessToken, authURL)
if err != nil {
return err
}

orgs, err := client.Organizations.List(ctx)
if err != nil {
return cmdutil.HandleError(err)
}

if len(orgs) > 0 {
defaultOrg := orgs[0].Name
writableConfig := &config.FileConfig{
Expand All @@ -126,3 +122,36 @@ func writeDefaultOrganization(ctx context.Context, accessToken, authURL string)

return nil
}

func hasOrg(ctx context.Context, org, accessToken, authURL string) (bool, error) {
currentOrgs, err := listCurrentOrgs(ctx, accessToken, authURL)
if err != nil {
return false, err
}

for _, o := range currentOrgs {
if o.Name == org {
return true, nil
}
}

return false, nil
}

func listCurrentOrgs(ctx context.Context, accessToken, authURL string) ([]*planetscale.Organization, error) {
client, err := planetscale.NewClient(
planetscale.WithAccessToken(accessToken),
planetscale.WithBaseURL(authURL),
)
if err != nil {
return nil, err
}

orgs, err := client.Organizations.List(ctx)
if err != nil {
return nil, cmdutil.HandleError(err)
}

return orgs, nil

}

0 comments on commit d32a799

Please sign in to comment.