-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
resource_user.go
294 lines (238 loc) · 6.97 KB
/
resource_user.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
package main
import (
"fmt"
"log"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/pactflow/terraform/broker"
"github.com/pactflow/terraform/client"
)
func user() *schema.Resource {
return &schema.Resource{
Create: userCreate,
Update: userUpdate,
Read: userRead,
Delete: userDelete,
Importer: &schema.ResourceImporter{State: schema.ImportStatePassthrough},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
Description: "Name of the User",
},
"email": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Description: "Email address of the user",
},
"active": {
Type: schema.TypeBool,
Optional: true,
Default: true,
Description: "Active status of the user",
},
"uuid": {
Type: schema.TypeString,
Computed: true,
Description: "The UUID of user",
},
"type": {
Type: schema.TypeString,
Default: allowedUserTypes[userType],
Description: "The type of user (regular/system)",
Optional: true,
ValidateFunc: validateUserType,
},
"roles": {
Type: schema.TypeSet,
Optional: true,
Description: "A list of roles (as uuids) to apply to the user",
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
},
}
}
const (
userType = "user"
systemType = "system"
)
// Special role that can't be assigned via API: https://github.com/pactflow/terraform-provider-pact/issues/22
const TEAM_ADMINISTRATOR_ROLE = "d635f960-88f2-4f13-8043-4641a02dffa0"
var allowedUserTypes = map[string]broker.UserType{
userType: broker.RegularUser,
systemType: broker.SystemAccount,
}
func userTypeAsString(t broker.UserType) string {
for k, v := range allowedUserTypes {
if v == t {
return k
}
}
return ""
}
func validateUserType(val interface{}, key string) (warns []string, errs []error) {
v := val.(string)
if _, ok := allowedUserTypes[v]; !ok {
errs = append(errs, fmt.Errorf("%q must be one of the allowed types %v, got %v", key, allowedUserTypes, v))
}
return
}
func userCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*client.Client)
user := getUserFromState(d)
roles := ExpandStringSet(d.Get("roles").(*schema.Set))
log.Println("[DEBUG] creating user", user, roles)
var created *broker.User
var err error
if user.Type == broker.SystemAccount {
created, err = client.CreateSystemAccount(user)
} else {
created, err = client.CreateUser(user)
}
if err != nil {
return err
}
d.SetId(created.UUID)
setUserState(d, *created)
log.Println("[DEBUG] updating user roles", d.Id(), roles)
err = client.SetUserRoles(d.Id(), broker.SetUserRolesRequest{
Roles: roles,
})
if err != nil {
// Creating a user is a non-atomic transaction, because roles is a separate API call
d.Partial(true)
log.Println("[ERROR] error updating user roles", err)
return fmt.Errorf("error updating roles for user (%s / %s): %w", d.Id(), created.Email, err)
}
d.Set("roles", roles)
return nil
}
func userUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*client.Client)
user := getUserFromState(d)
log.Println("[DEBUG] updating user", user)
updated, err := client.UpdateUser(user)
if err != nil {
return err
}
setUserState(d, *updated)
if d.HasChange("roles") {
roles := rolesFromStateChange(d)
log.Println("[DEBUG] updating user roles", roles)
err = client.SetUserRoles(d.Id(), broker.SetUserRolesRequest{
Roles: roles,
})
if err != nil {
d.Partial(true) // updating users is non-atomic, let the diff applier know this
log.Println("[ERROR] error updating user roles", err)
return fmt.Errorf("error updating roles for user (%s): %s", d.Id(), err)
}
d.Set("roles", roles)
}
return err
}
func userRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*client.Client)
uuid := d.Id()
log.Println("[DEBUG] reading user", uuid)
user, err := client.ReadUser(uuid)
if err == nil {
d.SetId(user.UUID)
setUserState(d, *user)
}
return err
}
func userDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*client.Client)
uuid := d.Id()
log.Println("[DEBUG] deleting user", d.Id())
// TODO: Delete attached resources Roles and Teams, because a Users aren't deleted, but simply disabled
user, err := client.ReadUser(uuid)
if err != nil {
log.Println("[ERROR] unable to fetch user for delete", user)
return fmt.Errorf("unable to fetch user for delete: %w", err)
}
log.Println("[DEBUG] have user for delete", user)
rolesToRemove := make([]string, len(user.Embedded.Roles))
for i, r := range user.Embedded.Roles {
rolesToRemove[i] = r.UUID
}
err = client.SetUserRoles(uuid, broker.SetUserRolesRequest{
Roles: []string{},
})
if err != nil {
return fmt.Errorf("unable to remove roles from user when deleting (disabling) user %s: %w", d.Id(), err)
}
for _, t := range user.Embedded.Teams {
err = client.DeleteTeamAssignment(t, *user)
if err != nil {
return fmt.Errorf("unable to remove user %s (%s) from team %s (%s): %w", d.Id(), user.Email, t.UUID, t.Name, err)
}
}
user.Embedded.Roles = nil
user.Embedded.Teams = nil
err = client.DeleteUser(*user)
if err != nil {
d.SetId("")
return fmt.Errorf("unable to delete (disable) user %s: %w", d.Id(), err)
}
return nil
}
func setUserState(d *schema.ResourceData, user broker.User) error {
log.Printf("[DEBUG] setting user state: %+v \n", user)
if err := d.Set("name", user.Name); err != nil {
log.Println("[ERROR] error setting key 'name'", err)
return err
}
if err := d.Set("email", user.Email); err != nil {
log.Println("[ERROR] error setting key 'email'", err)
return err
}
if err := d.Set("active", user.Active); err != nil {
log.Println("[ERROR] error setting key 'active'", err)
return err
}
if err := d.Set("uuid", user.UUID); err != nil {
log.Println("[ERROR] error setting key 'uuid'", err)
return err
}
if err := d.Set("type", user.Type); err != nil {
log.Println("[ERROR] error setting key 'type'", err)
return err
}
if err := d.Set("roles", rolesFromUser(user)); err != nil {
log.Println("[ERROR] error setting key 'roles'", err)
return err
}
return nil
}
func rolesFromUser(u broker.User) []string {
roles := make([]string, 0)
for _, r := range u.Embedded.Roles {
// Exclude the team administrator role
// See https://github.com/pactflow/terraform-provider-pact/issues/22
if r.UUID != TEAM_ADMINISTRATOR_ROLE {
roles = append(roles, r.UUID)
}
}
return roles
}
func rolesFromStateChange(d *schema.ResourceData) []string {
return ExpandStringSet(d.Get("roles").(*schema.Set))
}
func getUserFromState(d *schema.ResourceData) broker.User {
uuid := d.Id()
name := d.Get("name").(string)
email := d.Get("email").(string)
active := d.Get("active").(bool)
userType := d.Get("type").(string)
return broker.User{
UUID: uuid,
Email: email,
Active: active,
Name: name,
Type: allowedUserTypes[userType],
}
}