forked from osodevops/terraform-provider-workos
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathresource_user.go
More file actions
579 lines (517 loc) · 18.1 KB
/
Copy pathresource_user.go
File metadata and controls
579 lines (517 loc) · 18.1 KB
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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
// Copyright (c) OSO DevOps
// SPDX-License-Identifier: MPL-2.0
package provider
import (
"context"
"fmt"
"time"
"github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/booldefault"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/mapplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-log/tflog"
"github.com/osodevops/terraform-provider-workos/internal/client"
)
// Ensure provider defined types fully satisfy framework interfaces.
var _ resource.Resource = &UserResource{}
var _ resource.ResourceWithImportState = &UserResource{}
func NewUserResource() resource.Resource {
return &UserResource{}
}
// UserResource defines the resource implementation.
type UserResource struct {
client *client.Client
}
// UserResourceModel describes the resource data model.
type UserResourceModel struct {
ID types.String `tfsdk:"id"`
Email types.String `tfsdk:"email"`
EmailVerified types.Bool `tfsdk:"email_verified"`
FirstName types.String `tfsdk:"first_name"`
LastName types.String `tfsdk:"last_name"`
Password types.String `tfsdk:"password"`
PasswordHash types.String `tfsdk:"password_hash"`
PasswordHashType types.String `tfsdk:"password_hash_type"`
ExternalID types.String `tfsdk:"external_id"`
Metadata types.Map `tfsdk:"metadata"`
Locale types.String `tfsdk:"locale"`
ProfilePictureURL types.String `tfsdk:"profile_picture_url"`
CreatedAt types.String `tfsdk:"created_at"`
UpdatedAt types.String `tfsdk:"updated_at"`
}
func (r *UserResource) Metadata(ctx context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_user"
}
func (r *UserResource) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) {
resp.Schema = schema.Schema{
Description: "Manages a WorkOS AuthKit User.",
MarkdownDescription: `
Manages a WorkOS AuthKit User.
Users are the core identity entity in WorkOS AuthKit. They can authenticate
via various methods (password, magic link, SSO, OAuth) and be members of
one or more organizations.
## Example Usage
### Basic User
` + "```hcl" + `
resource "workos_user" "example" {
email = "user@example.com"
first_name = "John"
last_name = "Doe"
email_verified = true
}
` + "```" + `
### User with External ID and Metadata
` + "```hcl" + `
resource "workos_user" "with_metadata" {
email = "user@example.com"
first_name = "Jane"
last_name = "Smith"
external_id = "ext-12345"
email_verified = true
metadata = {
department = "Engineering"
timezone = "America/New_York"
}
}
` + "```" + `
### User with Password
` + "```hcl" + `
resource "workos_user" "with_password" {
email = "user@example.com"
first_name = "Jane"
last_name = "Smith"
password = var.user_password
email_verified = true
}
` + "```" + `
## Import
Users can be imported using the user ID:
` + "```shell" + `
terraform import workos_user.example user_01HXYZ...
` + "```" + `
**Note:** The password cannot be imported and must be set in configuration
if password authentication is required.
`,
Attributes: map[string]schema.Attribute{
"id": schema.StringAttribute{
Description: "The unique identifier of the user.",
MarkdownDescription: "The unique identifier of the user (e.g., `user_01HXYZ...`).",
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"email": schema.StringAttribute{
Description: "The user's email address.",
MarkdownDescription: "The user's email address. Must be unique across all users.",
Required: true,
},
"email_verified": schema.BoolAttribute{
Description: "Whether the user's email address has been verified.",
MarkdownDescription: "Whether the user's email address has been verified. Defaults to `false`.",
Optional: true,
Computed: true,
Default: booldefault.StaticBool(false),
},
"first_name": schema.StringAttribute{
Description: "The user's first name.",
MarkdownDescription: "The user's first name.",
Optional: true,
},
"last_name": schema.StringAttribute{
Description: "The user's last name.",
MarkdownDescription: "The user's last name.",
Optional: true,
},
"password": schema.StringAttribute{
Description: "The user's password. Write-only, not returned by API.",
MarkdownDescription: "The user's password. This is a write-only field and is not returned by the API. Only used during user creation.",
Optional: true,
Sensitive: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"password_hash": schema.StringAttribute{
Description: "A pre-hashed password. Write-only, not returned by API.",
MarkdownDescription: "A pre-hashed password (bcrypt or argon2). This is a write-only field and is not returned by the API. Use this if you're migrating users with existing password hashes.",
Optional: true,
Sensitive: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"password_hash_type": schema.StringAttribute{
Description: "The type of password hash. Write-only, used with password_hash.",
MarkdownDescription: "The type of password hash (e.g., `bcrypt`, `argon2`). This is a write-only field used only during creation alongside `password_hash`.",
Optional: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"external_id": schema.StringAttribute{
Description: "An external identifier for the user.",
MarkdownDescription: "An external identifier for the user. Useful for mapping to identifiers in external systems.",
Optional: true,
Computed: true,
},
"metadata": schema.MapAttribute{
Description: "Custom metadata for the user.",
MarkdownDescription: "Custom metadata for the user as key-value string pairs.",
Optional: true,
Computed: true,
ElementType: types.StringType,
PlanModifiers: []planmodifier.Map{
mapplanmodifier.UseStateForUnknown(),
},
},
"locale": schema.StringAttribute{
Description: "The user's locale.",
MarkdownDescription: "The user's locale (e.g., `en-US`). Set by the system based on user activity.",
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"profile_picture_url": schema.StringAttribute{
Description: "URL of the user's profile picture.",
MarkdownDescription: "URL of the user's profile picture.",
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"created_at": schema.StringAttribute{
Description: "The timestamp when the user was created.",
MarkdownDescription: "The timestamp when the user was created (RFC3339 format).",
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"updated_at": schema.StringAttribute{
Description: "The timestamp when the user was last updated.",
MarkdownDescription: "The timestamp when the user was last updated (RFC3339 format).",
Computed: true,
PlanModifiers: []planmodifier.String{
useStateForUnknownIfConfigUnchanged{
configAttributes: []path.Path{
path.Root("email"),
path.Root("email_verified"),
path.Root("first_name"),
path.Root("last_name"),
path.Root("external_id"),
path.Root("metadata"),
},
},
},
},
},
}
}
func (r *UserResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
if req.ProviderData == nil {
return
}
c, ok := req.ProviderData.(*client.Client)
if !ok {
resp.Diagnostics.AddError(
"Unexpected Resource Configure Type",
fmt.Sprintf("Expected *client.Client, got: %T. Please report this issue to the provider developers.", req.ProviderData),
)
return
}
r.client = c
}
func (r *UserResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
var plan UserResourceModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
tflog.Debug(ctx, "Creating user", map[string]any{
"email": plan.Email.ValueString(),
})
createReq := &client.UserCreateRequest{
Email: plan.Email.ValueString(),
EmailVerified: plan.EmailVerified.ValueBool(),
}
if !plan.FirstName.IsNull() {
createReq.FirstName = plan.FirstName.ValueString()
}
if !plan.LastName.IsNull() {
createReq.LastName = plan.LastName.ValueString()
}
if !plan.Password.IsNull() {
createReq.Password = plan.Password.ValueString()
}
if !plan.PasswordHash.IsNull() {
createReq.PasswordHash = plan.PasswordHash.ValueString()
}
if !plan.PasswordHashType.IsNull() {
createReq.PasswordHashType = plan.PasswordHashType.ValueString()
}
if !plan.ExternalID.IsNull() && !plan.ExternalID.IsUnknown() {
createReq.ExternalID = plan.ExternalID.ValueString()
}
if !plan.Metadata.IsNull() && !plan.Metadata.IsUnknown() {
metadata := make(map[string]string)
resp.Diagnostics.Append(plan.Metadata.ElementsAs(ctx, &metadata, false)...)
if resp.Diagnostics.HasError() {
return
}
createReq.Metadata = metadata
}
user, err := r.client.CreateUser(ctx, createReq)
if err != nil {
resp.Diagnostics.AddError(
"Error Creating User",
"Could not create user, unexpected error: "+err.Error(),
)
return
}
// Map response to state
plan.ID = types.StringValue(user.ID)
plan.Email = types.StringValue(user.Email)
plan.EmailVerified = types.BoolValue(user.EmailVerified)
if user.FirstName != "" {
plan.FirstName = types.StringValue(user.FirstName)
}
if user.LastName != "" {
plan.LastName = types.StringValue(user.LastName)
}
if user.ProfilePictureURL != "" {
plan.ProfilePictureURL = types.StringValue(user.ProfilePictureURL)
} else {
plan.ProfilePictureURL = types.StringNull()
}
if user.ExternalID != "" {
plan.ExternalID = types.StringValue(user.ExternalID)
} else {
plan.ExternalID = types.StringNull()
}
if len(user.Metadata) > 0 {
metadataMap, diags := types.MapValueFrom(ctx, types.StringType, user.Metadata)
resp.Diagnostics.Append(diags...)
plan.Metadata = metadataMap
} else {
plan.Metadata = types.MapNull(types.StringType)
}
if user.Locale != "" {
plan.Locale = types.StringValue(user.Locale)
} else {
plan.Locale = types.StringNull()
}
plan.CreatedAt = types.StringValue(user.CreatedAt.Format(time.RFC3339))
plan.UpdatedAt = types.StringValue(user.UpdatedAt.Format(time.RFC3339))
tflog.Info(ctx, "Created user", map[string]any{
"id": user.ID,
"email": user.Email,
})
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
}
func (r *UserResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
var state UserResourceModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
tflog.Debug(ctx, "Reading user", map[string]any{
"id": state.ID.ValueString(),
})
user, err := r.client.GetUser(ctx, state.ID.ValueString())
if err != nil {
if client.IsNotFound(err) {
tflog.Info(ctx, "User not found, removing from state", map[string]any{
"id": state.ID.ValueString(),
})
resp.State.RemoveResource(ctx)
return
}
resp.Diagnostics.AddError(
"Error Reading User",
"Could not read user ID "+state.ID.ValueString()+": "+err.Error(),
)
return
}
// Map response to state
state.Email = types.StringValue(user.Email)
state.EmailVerified = types.BoolValue(user.EmailVerified)
if user.FirstName != "" {
state.FirstName = types.StringValue(user.FirstName)
} else {
state.FirstName = types.StringNull()
}
if user.LastName != "" {
state.LastName = types.StringValue(user.LastName)
} else {
state.LastName = types.StringNull()
}
if user.ProfilePictureURL != "" {
state.ProfilePictureURL = types.StringValue(user.ProfilePictureURL)
} else {
state.ProfilePictureURL = types.StringNull()
}
if user.ExternalID != "" {
state.ExternalID = types.StringValue(user.ExternalID)
} else {
state.ExternalID = types.StringNull()
}
if len(user.Metadata) > 0 {
metadataMap, diags := types.MapValueFrom(ctx, types.StringType, user.Metadata)
resp.Diagnostics.Append(diags...)
state.Metadata = metadataMap
} else {
state.Metadata = types.MapNull(types.StringType)
}
if user.Locale != "" {
state.Locale = types.StringValue(user.Locale)
} else {
state.Locale = types.StringNull()
}
state.CreatedAt = types.StringValue(user.CreatedAt.Format(time.RFC3339))
state.UpdatedAt = types.StringValue(user.UpdatedAt.Format(time.RFC3339))
// Note: Password, PasswordHash, and PasswordHashType are not returned by the API, preserve state values
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
}
func (r *UserResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
var plan UserResourceModel
var state UserResourceModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
tflog.Debug(ctx, "Updating user", map[string]any{
"id": state.ID.ValueString(),
"email": plan.Email.ValueString(),
})
// Skip update if no user-configurable attributes changed
if plan.Email.Equal(state.Email) &&
plan.EmailVerified.Equal(state.EmailVerified) &&
plan.FirstName.Equal(state.FirstName) &&
plan.LastName.Equal(state.LastName) &&
plan.ExternalID.Equal(state.ExternalID) &&
plan.Metadata.Equal(state.Metadata) {
plan.ID = state.ID
plan.CreatedAt = state.CreatedAt
plan.UpdatedAt = state.UpdatedAt
plan.ProfilePictureURL = state.ProfilePictureURL
plan.Locale = state.Locale
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
return
}
updateReq := &client.UserUpdateRequest{}
// Always include email_verified — the API may reset it when the email changes.
emailVerified := plan.EmailVerified.ValueBool()
updateReq.EmailVerified = &emailVerified
if !plan.Email.Equal(state.Email) {
updateReq.Email = plan.Email.ValueString()
}
if !plan.FirstName.Equal(state.FirstName) {
updateReq.FirstName = plan.FirstName.ValueString()
}
if !plan.LastName.Equal(state.LastName) {
updateReq.LastName = plan.LastName.ValueString()
}
if !plan.ExternalID.Equal(state.ExternalID) {
updateReq.ExternalID = plan.ExternalID.ValueString()
}
if !plan.Metadata.Equal(state.Metadata) && !plan.Metadata.IsUnknown() {
metadata := make(map[string]string)
resp.Diagnostics.Append(plan.Metadata.ElementsAs(ctx, &metadata, false)...)
if resp.Diagnostics.HasError() {
return
}
updateReq.Metadata = metadata
}
user, err := r.client.UpdateUser(ctx, state.ID.ValueString(), updateReq)
if err != nil {
resp.Diagnostics.AddError(
"Error Updating User",
"Could not update user, unexpected error: "+err.Error(),
)
return
}
// Map response to state
plan.ID = state.ID
plan.Email = types.StringValue(user.Email)
plan.EmailVerified = types.BoolValue(user.EmailVerified)
if user.FirstName != "" {
plan.FirstName = types.StringValue(user.FirstName)
}
if user.LastName != "" {
plan.LastName = types.StringValue(user.LastName)
}
if user.ProfilePictureURL != "" {
plan.ProfilePictureURL = types.StringValue(user.ProfilePictureURL)
} else {
plan.ProfilePictureURL = types.StringNull()
}
if user.ExternalID != "" {
plan.ExternalID = types.StringValue(user.ExternalID)
} else {
plan.ExternalID = types.StringNull()
}
if len(user.Metadata) > 0 {
metadataMap, diags := types.MapValueFrom(ctx, types.StringType, user.Metadata)
resp.Diagnostics.Append(diags...)
plan.Metadata = metadataMap
} else {
plan.Metadata = types.MapNull(types.StringType)
}
if user.Locale != "" {
plan.Locale = types.StringValue(user.Locale)
} else {
plan.Locale = types.StringNull()
}
plan.CreatedAt = state.CreatedAt
plan.UpdatedAt = types.StringValue(user.UpdatedAt.Format(time.RFC3339))
tflog.Info(ctx, "Updated user", map[string]any{
"id": user.ID,
})
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
}
func (r *UserResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
var state UserResourceModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
tflog.Debug(ctx, "Deleting user", map[string]any{
"id": state.ID.ValueString(),
})
err := r.client.DeleteUser(ctx, state.ID.ValueString())
if err != nil {
if client.IsNotFound(err) {
tflog.Info(ctx, "User already deleted", map[string]any{
"id": state.ID.ValueString(),
})
return
}
resp.Diagnostics.AddError(
"Error Deleting User",
"Could not delete user, unexpected error: "+err.Error(),
)
return
}
tflog.Info(ctx, "Deleted user", map[string]any{
"id": state.ID.ValueString(),
})
}
func (r *UserResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
tflog.Debug(ctx, "Importing user", map[string]any{
"id": req.ID,
})
resource.ImportStatePassthroughID(ctx, path.Root("id"), req, resp)
// Note: Password and PasswordHash cannot be imported
resp.Diagnostics.AddWarning(
"Write-Only Fields Not Imported",
"The user's password, password_hash, and password_hash_type cannot be imported from the API. "+
"If password authentication is required, you must set these attributes in your configuration.",
)
}