diff --git a/auth0/resource_auth0_user.go b/auth0/resource_auth0_user.go index 7e218ec8e..6b60dfd96 100644 --- a/auth0/resource_auth0_user.go +++ b/auth0/resource_auth0_user.go @@ -120,11 +120,9 @@ func readUser(ctx context.Context, d *schema.ResourceData, m interface{}) diag.D api := m.(*management.Management) user, err := api.User.Read(d.Id()) if err != nil { - if mErr, ok := err.(management.Error); ok { - if mErr.Status() == http.StatusNotFound { - d.SetId("") - return nil - } + if err, ok := err.(management.Error); ok && err.Status() == http.StatusNotFound { + d.SetId("") + return nil } return diag.FromErr(err) } @@ -250,19 +248,52 @@ func expandUser(d *schema.ResourceData) (*management.User, error) { Blocked: Bool(d, "blocked"), } - userMeta, err := JSON(d, "user_metadata") + if d.HasChange("user_metadata") { + userMetadata, err := expandMetadata(d, "user") + if err != nil { + return nil, err + } + user.UserMetadata = &userMetadata + } + + if d.HasChange("app_metadata") { + appMetadata, err := expandMetadata(d, "app") + if err != nil { + return nil, err + } + user.AppMetadata = &appMetadata + } + + return user, nil +} + +func expandMetadata(d *schema.ResourceData, metadataType string) (map[string]interface{}, error) { + oldMetadata, newMetadata := d.GetChange(metadataType + "_metadata") + if oldMetadata == "" { + return JSON(d, metadataType+"_metadata") + } + + if newMetadata == "" { + return map[string]interface{}{}, nil + } + + oldMap, err := structure.ExpandJsonFromString(oldMetadata.(string)) if err != nil { - return nil, err + return map[string]interface{}{}, err } - user.UserMetadata = &userMeta - appMeta, err := JSON(d, "app_metadata") + newMap, err := structure.ExpandJsonFromString(newMetadata.(string)) if err != nil { - return nil, err + return map[string]interface{}{}, err } - user.AppMetadata = &appMeta - return user, nil + for key := range oldMap { + if _, ok := newMap[key]; !ok { + newMap[key] = nil + } + } + + return newMap, nil } func flattenUserRoles(roleList *management.RoleList) []interface{} { diff --git a/auth0/resource_auth0_user_test.go b/auth0/resource_auth0_user_test.go index 519174de9..575389000 100644 --- a/auth0/resource_auth0_user_test.go +++ b/auth0/resource_auth0_user_test.go @@ -75,22 +75,10 @@ resource auth0_user user { family_name = "Lastname" nickname = "{{.testName}}" picture = "https://www.example.com/picture.jpg" - user_metadata = <