Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[8/X] Refactor orgs to allow for empty fields and remove deprecated field #343

Merged
merged 2 commits into from
Oct 7, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 0 additions & 13 deletions docs/resources/organization.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,6 @@ resource "auth0_organization" "my_organization" {
### Optional

- `branding` (Block List, Max: 1) Defines how to style the login pages. (see [below for nested schema](#nestedblock--branding))
- `connections` (Block Set, Deprecated) (see [below for nested schema](#nestedblock--connections))
- `display_name` (String) Friendly name of this organization.
- `metadata` (Map of String) Metadata associated with the organization. Maximum of 10 metadata properties allowed.

Expand All @@ -60,18 +59,6 @@ Optional:
- `colors` (Map of String) Color scheme used to customize the login pages.
- `logo_url` (String) URL of logo to display on login page.


<a id="nestedblock--connections"></a>
### Nested Schema for `connections`

Required:

- `connection_id` (String) The connection ID of the connection to add to the organization.

Optional:

- `assign_membership_on_login` (Boolean) When `true`, all users that log in with this connection will be automatically granted membership in the organization. When `false`, users must be granted membership in the organization before logging in with this connection.

## Import

Import is supported using the following syntax:
Expand Down
170 changes: 37 additions & 133 deletions internal/provider/resource_auth0_organization.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@ package provider

import (
"context"
"fmt"
"net/http"

"github.com/auth0/go-auth0"
"github.com/auth0/go-auth0/management"
"github.com/hashicorp/go-cty/cty"
"github.com/hashicorp/go-multierror"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"

"github.com/auth0/terraform-provider-auth0/internal/value"
)

func newOrganization() *schema.Resource {
Expand Down Expand Up @@ -67,100 +68,59 @@ func newOrganization() *schema.Resource {
Elem: &schema.Schema{Type: schema.TypeString},
Description: "Metadata associated with the organization. Maximum of 10 metadata properties allowed.",
},
"connections": {
Type: schema.TypeSet,
Optional: true,
Computed: true,
Deprecated: "Management of organizations through this property has been deprecated in favor of the " +
"`auth0_organization_connection` resource and will be deleted in future versions. It is " +
"advised to migrate all managed organization connections to the new resource type.",
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"connection_id": {
Type: schema.TypeString,
Required: true,
Description: "The connection ID of the connection to add to the organization.",
},
"assign_membership_on_login": {
Type: schema.TypeBool,
Optional: true,
Default: false,
Description: "When `true`, all users that log in with this connection will be " +
"automatically granted membership in the organization. When `false`, users must be " +
"granted membership in the organization before logging in with this connection.",
},
},
},
},
},
}
}

func createOrganization(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
organization := expandOrganization(d)

api := m.(*management.Management)

organization := expandOrganization(d)
if err := api.Organization.Create(organization); err != nil {
return diag.FromErr(err)
}

d.SetId(organization.GetID())

if err := updateOrganizationConnections(d, api); err != nil {
return diag.FromErr(fmt.Errorf("failed to update organization connections: %w", err))
}

return readOrganization(ctx, d, m)
}

func readOrganization(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
api := m.(*management.Management)

organization, err := api.Organization.Read(d.Id())
if err != nil {
if mErr, ok := err.(management.Error); ok {
if mErr.Status() == http.StatusNotFound {
d.SetId("")
return nil
}
if mErr, ok := err.(management.Error); ok && mErr.Status() == http.StatusNotFound {
d.SetId("")
return nil
}
return diag.FromErr(err)
}

organizationConnectionList, err := api.Organization.Connections(d.Id())
if err != nil {
return diag.FromErr(err)
}

result := multierror.Append(
d.Set("name", organization.Name),
d.Set("display_name", organization.DisplayName),
d.Set("branding", flattenOrganizationBranding(organization.Branding)),
d.Set("metadata", organization.Metadata),
d.Set("connections", flattenOrganizationConnections(organizationConnectionList)),
d.Set("name", organization.GetName()),
d.Set("display_name", organization.GetDisplayName()),
d.Set("branding", flattenOrganizationBranding(organization.GetBranding())),
d.Set("metadata", organization.GetMetadata()),
)

return diag.FromErr(result.ErrorOrNil())
}

func updateOrganization(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
organization := expandOrganization(d)

api := m.(*management.Management)

organization := expandOrganization(d)
if err := api.Organization.Update(d.Id(), organization); err != nil {
return diag.FromErr(err)
}

if d.HasChange("connections") {
if err := updateOrganizationConnections(d, api); err != nil {
return diag.FromErr(fmt.Errorf("failed to update organization connections: %w", err))
}
}

return readOrganization(ctx, d, m)
}

func deleteOrganization(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
api := m.(*management.Management)

if err := api.Organization.Delete(d.Id()); err != nil {
if err, ok := err.(management.Error); ok && err.Status() == http.StatusNotFound {
d.SetId("")
Expand All @@ -169,79 +129,39 @@ func deleteOrganization(ctx context.Context, d *schema.ResourceData, m interface
return diag.FromErr(err)
}

d.SetId("")
return nil
}

func updateOrganizationConnections(d *schema.ResourceData, api *management.Management) error {
toAdd, toRemove := Diff(d, "connections")

connectionOperations := make(map[string]string)
toRemove.Elem(func(data ResourceData) {
oldConnectionID, _ := data.GetChange("connection_id")
connectionOperations[oldConnectionID.(string)] = "deleteConnection"
})

toAdd.Elem(func(data ResourceData) {
newConnectionID := data.Get("connection_id").(string)

if _, ok := connectionOperations[newConnectionID]; ok {
delete(connectionOperations, newConnectionID)
} else {
connectionOperations[newConnectionID] = "addConnection"
}
})

for key, value := range connectionOperations {
if value == "deleteConnection" {
if err := api.Organization.DeleteConnection(d.Id(), key); err != nil {
return err
}
}
if value == "addConnection" {
organizationConnection := &management.OrganizationConnection{
ConnectionID: auth0.String(key),
}
if err := api.Organization.AddConnection(d.Id(), organizationConnection); err != nil {
return err
}
}
}

var err error
Set(d, "connections").Elem(func(data ResourceData) {
connectionID := data.Get("connection_id").(string)
organizationConnection := &management.OrganizationConnection{
AssignMembershipOnLogin: Bool(data, "assign_membership_on_login"),
}

err = api.Organization.UpdateConnection(d.Id(), connectionID, organizationConnection)
if err != nil {
return
}
})

return err
}

func expandOrganization(d *schema.ResourceData) *management.Organization {
config := d.GetRawConfig()

organization := &management.Organization{
Name: String(d, "name"),
DisplayName: String(d, "display_name"),
Name: value.String(config.GetAttr("name")),
DisplayName: value.String(config.GetAttr("display_name")),
Branding: expandOrganizationBranding(config.GetAttr("branding")),
}

if d.HasChange("metadata") {
metadata := Map(d, "metadata")
organization.Metadata = &metadata
organization.Metadata = value.MapOfStrings(config.GetAttr("metadata"))
}

List(d, "branding").Elem(func(d ResourceData) {
organization.Branding = &management.OrganizationBranding{
LogoURL: String(d, "logo_url"),
Colors: Map(d, "colors"),
return organization
}

func expandOrganizationBranding(brandingList cty.Value) *management.OrganizationBranding {
var organizationBranding *management.OrganizationBranding

brandingList.ForEachElement(func(_ cty.Value, branding cty.Value) (stop bool) {
organizationBranding = &management.OrganizationBranding{
LogoURL: value.String(branding.GetAttr("logo_url")),
Colors: value.MapOfStrings(branding.GetAttr("colors")),
}

return stop
})

return organization
return organizationBranding
}

func flattenOrganizationBranding(organizationBranding *management.OrganizationBranding) []interface{} {
Expand All @@ -252,23 +172,7 @@ func flattenOrganizationBranding(organizationBranding *management.OrganizationBr
return []interface{}{
map[string]interface{}{
"logo_url": organizationBranding.GetLogoURL(),
"colors": organizationBranding.Colors,
"colors": organizationBranding.GetColors(),
},
}
}

func flattenOrganizationConnections(connectionList *management.OrganizationConnectionList) []interface{} {
if connectionList == nil {
return nil
}

connections := make([]interface{}, len(connectionList.OrganizationConnections))
for index, connection := range connectionList.OrganizationConnections {
connections[index] = map[string]interface{}{
"connection_id": connection.GetConnectionID(),
"assign_membership_on_login": connection.GetAssignMembershipOnLogin(),
}
}

return connections
}
14 changes: 10 additions & 4 deletions internal/provider/resource_auth0_organization_connection.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,9 +94,12 @@ func createOrganizationConnection(ctx context.Context, data *schema.ResourceData
api := meta.(*management.Management)

organizationID := data.Get("organization_id").(string)
connectionID := data.Get("connection_id").(string)
assignMembershipOnLogin := data.Get("assign_membership_on_login").(bool)

organizationConnection := &management.OrganizationConnection{
ConnectionID: String(data, "connection_id"),
AssignMembershipOnLogin: Bool(data, "assign_membership_on_login"),
ConnectionID: &connectionID,
AssignMembershipOnLogin: &assignMembershipOnLogin,
}

if err := api.Organization.AddConnection(organizationID, organizationConnection); err != nil {
Expand All @@ -113,6 +116,7 @@ func readOrganizationConnection(ctx context.Context, data *schema.ResourceData,

organizationID := data.Get("organization_id").(string)
connectionID := data.Get("connection_id").(string)

organizationConnection, err := api.Organization.Connection(organizationID, connectionID)
if err != nil {
return diag.FromErr(err)
Expand All @@ -132,9 +136,12 @@ func updateOrganizationConnection(ctx context.Context, data *schema.ResourceData

organizationID := data.Get("organization_id").(string)
connectionID := data.Get("connection_id").(string)
assignMembershipOnLogin := data.Get("assign_membership_on_login").(bool)

organizationConnection := &management.OrganizationConnection{
AssignMembershipOnLogin: Bool(data, "assign_membership_on_login"),
AssignMembershipOnLogin: &assignMembershipOnLogin,
}

if err := api.Organization.UpdateConnection(organizationID, connectionID, organizationConnection); err != nil {
return diag.FromErr(err)
}
Expand All @@ -157,6 +164,5 @@ func deleteOrganizationConnection(ctx context.Context, data *schema.ResourceData
}

data.SetId("")

return nil
}
Loading