|
| 1 | +// Copyright (c) HashiCorp, Inc. |
| 2 | +// SPDX-License-Identifier: MPL-2.0 |
| 3 | + |
| 4 | +package provider |
| 5 | + |
| 6 | +import ( |
| 7 | + "context" |
| 8 | + "fmt" |
| 9 | + "strings" |
| 10 | + |
| 11 | + "github.com/google/uuid" |
| 12 | + "github.com/hashicorp/terraform-plugin-framework-validators/setvalidator" |
| 13 | + "github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator" |
| 14 | + "github.com/hashicorp/terraform-plugin-framework/attr" |
| 15 | + "github.com/hashicorp/terraform-plugin-framework/path" |
| 16 | + "github.com/hashicorp/terraform-plugin-framework/resource" |
| 17 | + "github.com/hashicorp/terraform-plugin-framework/resource/schema" |
| 18 | + "github.com/hashicorp/terraform-plugin-framework/resource/schema/booldefault" |
| 19 | + "github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier" |
| 20 | + "github.com/hashicorp/terraform-plugin-framework/resource/schema/setdefault" |
| 21 | + "github.com/hashicorp/terraform-plugin-framework/resource/schema/stringdefault" |
| 22 | + "github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier" |
| 23 | + "github.com/hashicorp/terraform-plugin-framework/schema/validator" |
| 24 | + "github.com/hashicorp/terraform-plugin-framework/types" |
| 25 | + "github.com/hashicorp/terraform-plugin-log/tflog" |
| 26 | + |
| 27 | + "github.com/coder/coder/v2/codersdk" |
| 28 | +) |
| 29 | + |
| 30 | +// Ensure provider defined types fully satisfy framework interfaces. |
| 31 | +var _ resource.Resource = &UserResource{} |
| 32 | +var _ resource.ResourceWithImportState = &UserResource{} |
| 33 | + |
| 34 | +func NewUserResource() resource.Resource { |
| 35 | + return &UserResource{} |
| 36 | +} |
| 37 | + |
| 38 | +// UserResource defines the resource implementation. |
| 39 | +type UserResource struct { |
| 40 | + data *CoderdProviderData |
| 41 | +} |
| 42 | + |
| 43 | +// UserResourceModel describes the resource data model. |
| 44 | +type UserResourceModel struct { |
| 45 | + ID types.String `tfsdk:"id"` |
| 46 | + |
| 47 | + Username types.String `tfsdk:"username"` |
| 48 | + Name types.String `tfsdk:"name"` |
| 49 | + Email types.String `tfsdk:"email"` |
| 50 | + Roles types.Set `tfsdk:"roles"` // owner, template-admin, user-admin, auditor (member is implicit) |
| 51 | + LoginType types.String `tfsdk:"login_type"` // none, password, github, oidc |
| 52 | + Password types.String `tfsdk:"password"` // only when login_type is password |
| 53 | + Suspended types.Bool `tfsdk:"suspended"` |
| 54 | +} |
| 55 | + |
| 56 | +func (r *UserResource) Metadata(ctx context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) { |
| 57 | + resp.TypeName = req.ProviderTypeName + "_user" |
| 58 | +} |
| 59 | + |
| 60 | +func (r *UserResource) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) { |
| 61 | + resp.Schema = schema.Schema{ |
| 62 | + MarkdownDescription: "A user on the Coder deployment.", |
| 63 | + |
| 64 | + Attributes: map[string]schema.Attribute{ |
| 65 | + "id": schema.StringAttribute{ |
| 66 | + Computed: true, |
| 67 | + MarkdownDescription: "User ID", |
| 68 | + PlanModifiers: []planmodifier.String{ |
| 69 | + stringplanmodifier.UseStateForUnknown(), |
| 70 | + }, |
| 71 | + }, |
| 72 | + |
| 73 | + "username": schema.StringAttribute{ |
| 74 | + MarkdownDescription: "Username of the user.", |
| 75 | + Required: true, |
| 76 | + }, |
| 77 | + "name": schema.StringAttribute{ |
| 78 | + Computed: true, |
| 79 | + MarkdownDescription: "Display name of the user. Defaults to username.", |
| 80 | + Required: false, |
| 81 | + Optional: true, |
| 82 | + }, |
| 83 | + "email": schema.StringAttribute{ |
| 84 | + MarkdownDescription: "Email address of the user.", |
| 85 | + Required: true, |
| 86 | + }, |
| 87 | + "roles": schema.SetAttribute{ |
| 88 | + MarkdownDescription: "Roles assigned to the user. Valid roles are 'owner', 'template-admin', 'user-admin', and 'auditor'.", |
| 89 | + Required: false, |
| 90 | + Optional: true, |
| 91 | + Computed: true, |
| 92 | + ElementType: types.StringType, |
| 93 | + Validators: []validator.Set{ |
| 94 | + setvalidator.ValueStringsAre( |
| 95 | + stringvalidator.OneOf("owner", "template-admin", "user-admin", "auditor"), |
| 96 | + ), |
| 97 | + }, |
| 98 | + Default: setdefault.StaticValue(types.SetValueMust(types.StringType, []attr.Value{})), |
| 99 | + }, |
| 100 | + "login_type": schema.StringAttribute{ |
| 101 | + MarkdownDescription: "Type of login for the user. Valid types are 'none', 'password', 'github', and 'oidc'.", |
| 102 | + Required: false, |
| 103 | + Optional: true, |
| 104 | + Computed: true, |
| 105 | + Validators: []validator.String{ |
| 106 | + stringvalidator.OneOf("none", "password", "github", "oidc"), |
| 107 | + }, |
| 108 | + Default: stringdefault.StaticString("none"), |
| 109 | + }, |
| 110 | + "password": schema.StringAttribute{ |
| 111 | + MarkdownDescription: "Password for the user. Required when login_type is 'password'. Passwords are saved into the state as plain text and should only be used for testing purposes.", |
| 112 | + Required: false, |
| 113 | + Optional: true, |
| 114 | + Sensitive: true, |
| 115 | + }, |
| 116 | + "suspended": schema.BoolAttribute{ |
| 117 | + Computed: true, |
| 118 | + MarkdownDescription: "Whether the user is suspended.", |
| 119 | + Required: false, |
| 120 | + Optional: true, |
| 121 | + Default: booldefault.StaticBool(false), |
| 122 | + }, |
| 123 | + }, |
| 124 | + } |
| 125 | +} |
| 126 | + |
| 127 | +func (r *UserResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) { |
| 128 | + // Prevent panic if the provider has not been configured. |
| 129 | + if req.ProviderData == nil { |
| 130 | + return |
| 131 | + } |
| 132 | + |
| 133 | + client, ok := req.ProviderData.(*CoderdProviderData) |
| 134 | + |
| 135 | + if !ok { |
| 136 | + resp.Diagnostics.AddError( |
| 137 | + "Unexpected Resource Configure Type", |
| 138 | + fmt.Sprintf("Expected *codersdk.Client, got: %T. Please report this issue to the provider developers.", req.ProviderData), |
| 139 | + ) |
| 140 | + |
| 141 | + return |
| 142 | + } |
| 143 | + |
| 144 | + r.data = client |
| 145 | +} |
| 146 | + |
| 147 | +func (r *UserResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { |
| 148 | + var data UserResourceModel |
| 149 | + |
| 150 | + // Read Terraform plan data into the model |
| 151 | + resp.Diagnostics.Append(req.Plan.Get(ctx, &data)...) |
| 152 | + if resp.Diagnostics.HasError() { |
| 153 | + return |
| 154 | + } |
| 155 | + |
| 156 | + client := r.data.Client |
| 157 | + |
| 158 | + me, err := client.User(ctx, codersdk.Me) |
| 159 | + if err != nil { |
| 160 | + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Unable to get current user, got error: %s", err)) |
| 161 | + return |
| 162 | + } |
| 163 | + if len(me.OrganizationIDs) < 1 { |
| 164 | + resp.Diagnostics.AddError("Client Error", "User is not associated with any organizations") |
| 165 | + return |
| 166 | + } |
| 167 | + |
| 168 | + tflog.Trace(ctx, "creating user") |
| 169 | + loginType := codersdk.LoginTypeNone |
| 170 | + if data.LoginType.ValueString() != "" { |
| 171 | + loginType = codersdk.LoginType(data.LoginType.ValueString()) |
| 172 | + } |
| 173 | + user, err := client.CreateUser(ctx, codersdk.CreateUserRequest{ |
| 174 | + Email: data.Email.ValueString(), |
| 175 | + Username: data.Username.ValueString(), |
| 176 | + Password: data.Password.ValueString(), |
| 177 | + UserLoginType: loginType, |
| 178 | + OrganizationID: me.OrganizationIDs[0], |
| 179 | + }) |
| 180 | + if err != nil { |
| 181 | + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Unable to create user, got error: %s", err)) |
| 182 | + return |
| 183 | + } |
| 184 | + tflog.Trace(ctx, "successfully created user", map[string]any{ |
| 185 | + "id": user.ID.String(), |
| 186 | + }) |
| 187 | + data.ID = types.StringValue(user.ID.String()) |
| 188 | + |
| 189 | + tflog.Trace(ctx, "updating user profile") |
| 190 | + name := data.Username.ValueString() |
| 191 | + if data.Name.ValueString() != "" { |
| 192 | + name = data.Name.ValueString() |
| 193 | + } |
| 194 | + user, err = client.UpdateUserProfile(ctx, user.ID.String(), codersdk.UpdateUserProfileRequest{ |
| 195 | + Username: data.Username.ValueString(), |
| 196 | + Name: name, |
| 197 | + }) |
| 198 | + if err != nil { |
| 199 | + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Unable to update newly created user profile, got error: %s", err)) |
| 200 | + return |
| 201 | + } |
| 202 | + tflog.Trace(ctx, "successfully updated user profile") |
| 203 | + |
| 204 | + var roles []string |
| 205 | + resp.Diagnostics.Append( |
| 206 | + data.Roles.ElementsAs(ctx, &roles, false)..., |
| 207 | + ) |
| 208 | + tflog.Trace(ctx, "updating user roles", map[string]any{ |
| 209 | + "new_roles": roles, |
| 210 | + }) |
| 211 | + user, err = client.UpdateUserRoles(ctx, user.ID.String(), codersdk.UpdateRoles{ |
| 212 | + Roles: roles, |
| 213 | + }) |
| 214 | + if err != nil { |
| 215 | + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Unable to update newly created user roles, got error: %s", err)) |
| 216 | + return |
| 217 | + } |
| 218 | + tflog.Trace(ctx, "successfully updated user roles") |
| 219 | + |
| 220 | + if data.Suspended.ValueBool() { |
| 221 | + _, err = client.UpdateUserStatus(ctx, data.ID.ValueString(), codersdk.UserStatus("suspended")) |
| 222 | + } |
| 223 | + if err != nil { |
| 224 | + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Unable to update user status, got error: %s", err)) |
| 225 | + return |
| 226 | + } |
| 227 | + // Save data into Terraform state |
| 228 | + resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) |
| 229 | +} |
| 230 | + |
| 231 | +func (r *UserResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { |
| 232 | + var data UserResourceModel |
| 233 | + |
| 234 | + // Read Terraform prior state data into the model |
| 235 | + resp.Diagnostics.Append(req.State.Get(ctx, &data)...) |
| 236 | + |
| 237 | + if resp.Diagnostics.HasError() { |
| 238 | + return |
| 239 | + } |
| 240 | + |
| 241 | + client := r.data.Client |
| 242 | + |
| 243 | + user, err := client.User(ctx, data.ID.ValueString()) |
| 244 | + if err != nil { |
| 245 | + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Unable to get current user, got error: %s", err)) |
| 246 | + return |
| 247 | + } |
| 248 | + if len(user.OrganizationIDs) < 1 { |
| 249 | + resp.Diagnostics.AddError("Client Error", "User is not associated with any organizations") |
| 250 | + return |
| 251 | + } |
| 252 | + |
| 253 | + data.Email = types.StringValue(user.Email) |
| 254 | + data.Name = types.StringValue(user.Name) |
| 255 | + data.Username = types.StringValue(user.Username) |
| 256 | + roles := make([]attr.Value, 0, len(user.Roles)) |
| 257 | + for _, role := range user.Roles { |
| 258 | + roles = append(roles, types.StringValue(role.Name)) |
| 259 | + } |
| 260 | + data.Roles = types.SetValueMust(types.StringType, roles) |
| 261 | + data.LoginType = types.StringValue(string(user.LoginType)) |
| 262 | + data.Suspended = types.BoolValue(user.Status == codersdk.UserStatusSuspended) |
| 263 | + |
| 264 | + // Save updated data into Terraform state |
| 265 | + resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) |
| 266 | +} |
| 267 | + |
| 268 | +func (r *UserResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { |
| 269 | + var data UserResourceModel |
| 270 | + |
| 271 | + // Read Terraform plan data into the model |
| 272 | + resp.Diagnostics.Append(req.Plan.Get(ctx, &data)...) |
| 273 | + |
| 274 | + if resp.Diagnostics.HasError() { |
| 275 | + return |
| 276 | + } |
| 277 | + |
| 278 | + client := r.data.Client |
| 279 | + |
| 280 | + user, err := client.User(ctx, data.ID.ValueString()) |
| 281 | + if err != nil { |
| 282 | + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Unable to get current user, got error: %s", err)) |
| 283 | + return |
| 284 | + } |
| 285 | + if len(user.OrganizationIDs) < 1 { |
| 286 | + resp.Diagnostics.AddError("Client Error", "User is not associated with any organizations") |
| 287 | + return |
| 288 | + } |
| 289 | + |
| 290 | + tflog.Trace(ctx, "updating user", map[string]any{ |
| 291 | + "new_username": data.Username.ValueString(), |
| 292 | + "new_name": data.Name.ValueString(), |
| 293 | + }) |
| 294 | + _, err = client.UpdateUserProfile(ctx, user.ID.String(), codersdk.UpdateUserProfileRequest{ |
| 295 | + Username: data.Username.ValueString(), |
| 296 | + Name: data.Name.ValueString(), |
| 297 | + }) |
| 298 | + if err != nil { |
| 299 | + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Unable to update user profile, got error: %s", err)) |
| 300 | + return |
| 301 | + } |
| 302 | + tflog.Trace(ctx, "successfully updated user profile") |
| 303 | + |
| 304 | + var roles []string |
| 305 | + resp.Diagnostics.Append( |
| 306 | + data.Roles.ElementsAs(ctx, &roles, false)..., |
| 307 | + ) |
| 308 | + tflog.Trace(ctx, "updating user roles", map[string]any{ |
| 309 | + "new_roles": roles, |
| 310 | + }) |
| 311 | + _, err = client.UpdateUserRoles(ctx, user.ID.String(), codersdk.UpdateRoles{ |
| 312 | + Roles: roles, |
| 313 | + }) |
| 314 | + if err != nil { |
| 315 | + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Unable to update user roles, got error: %s", err)) |
| 316 | + return |
| 317 | + } |
| 318 | + tflog.Trace(ctx, "successfully updated user roles") |
| 319 | + |
| 320 | + tflog.Trace(ctx, "updating password") |
| 321 | + err = client.UpdateUserPassword(ctx, user.ID.String(), codersdk.UpdateUserPasswordRequest{ |
| 322 | + Password: data.Password.ValueString(), |
| 323 | + }) |
| 324 | + if err != nil && !strings.Contains(err.Error(), "New password cannot match old password.") { |
| 325 | + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Unable to update password, got error: %s", err)) |
| 326 | + return |
| 327 | + } |
| 328 | + tflog.Trace(ctx, "successfully updated password") |
| 329 | + |
| 330 | + var statusErr error |
| 331 | + if data.Suspended.ValueBool() { |
| 332 | + _, statusErr = client.UpdateUserStatus(ctx, data.ID.ValueString(), codersdk.UserStatus("suspended")) |
| 333 | + } |
| 334 | + if !data.Suspended.ValueBool() && user.Status == codersdk.UserStatusSuspended { |
| 335 | + _, statusErr = client.UpdateUserStatus(ctx, data.ID.ValueString(), codersdk.UserStatus("active")) |
| 336 | + } |
| 337 | + if statusErr != nil { |
| 338 | + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Unable to update user status, got error: %s", err)) |
| 339 | + return |
| 340 | + } |
| 341 | + |
| 342 | + // Save updated data into Terraform state |
| 343 | + resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) |
| 344 | +} |
| 345 | + |
| 346 | +func (r *UserResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { |
| 347 | + var data UserResourceModel |
| 348 | + |
| 349 | + // Read Terraform prior state data into the model |
| 350 | + resp.Diagnostics.Append(req.State.Get(ctx, &data)...) |
| 351 | + |
| 352 | + if resp.Diagnostics.HasError() { |
| 353 | + return |
| 354 | + } |
| 355 | + |
| 356 | + client := r.data.Client |
| 357 | + |
| 358 | + id, err := uuid.Parse(data.ID.ValueString()) |
| 359 | + if err != nil { |
| 360 | + resp.Diagnostics.AddError("Data Error", fmt.Sprintf("Unable to parse user ID, got error: %s", err)) |
| 361 | + return |
| 362 | + } |
| 363 | + tflog.Trace(ctx, "deleting user") |
| 364 | + err = client.DeleteUser(ctx, id) |
| 365 | + if err != nil { |
| 366 | + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Unable to delete user, got error: %s", err)) |
| 367 | + return |
| 368 | + } |
| 369 | + tflog.Trace(ctx, "successfully deleted user") |
| 370 | +} |
| 371 | + |
| 372 | +func (r *UserResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) { |
| 373 | + resource.ImportStatePassthroughID(ctx, path.Root("id"), req, resp) |
| 374 | +} |
0 commit comments