| 26 | } |
| 27 | |
| 28 | func Validate[Role codersdk.WorkspaceRole | codersdk.TemplateRole | codersdk.ChatRole]( |
| 29 | ctx context.Context, |
| 30 | db database.Store, |
| 31 | v UpdateValidator[Role], |
| 32 | ) []codersdk.ValidationError { |
| 33 | // nolint:gocritic // Validate requires full read access to users and groups |
| 34 | ctx = dbauthz.AsSystemRestricted(ctx) |
| 35 | var validErrs []codersdk.ValidationError |
| 36 | |
| 37 | groupRoles, groupsField := v.Groups() |
| 38 | groupIDs := make([]uuid.UUID, 0, len(groupRoles)) |
| 39 | for idStr, role := range groupRoles { |
| 40 | // Validate the provided role names |
| 41 | if err := v.ValidateRole(role); err != nil { |
| 42 | validErrs = append(validErrs, codersdk.ValidationError{ |
| 43 | Field: groupsField, |
| 44 | Detail: err.Error(), |
| 45 | }) |
| 46 | } |
| 47 | // Validate that the IDs are UUIDs |
| 48 | id, err := uuid.Parse(idStr) |
| 49 | if err != nil { |
| 50 | validErrs = append(validErrs, codersdk.ValidationError{ |
| 51 | Field: groupsField, |
| 52 | Detail: fmt.Sprintf("%v is not a valid UUID.", idStr), |
| 53 | }) |
| 54 | continue |
| 55 | } |
| 56 | // Don't check if the ID exists when setting the role to |
| 57 | // WorkspaceRoleDeleted or TemplateRoleDeleted. They might've existing at |
| 58 | // some point and got deleted. If we report that as an error here then they |
| 59 | // can't be removed. |
| 60 | if string(role) == "" { |
| 61 | continue |
| 62 | } |
| 63 | groupIDs = append(groupIDs, id) |
| 64 | } |
| 65 | |
| 66 | // Validate that the groups exist |
| 67 | groupValidation, err := db.ValidateGroupIDs(ctx, groupIDs) |
| 68 | if err != nil { |
| 69 | validErrs = append(validErrs, codersdk.ValidationError{ |
| 70 | Field: groupsField, |
| 71 | Detail: fmt.Sprintf("failed to validate group IDs: %v", err.Error()), |
| 72 | }) |
| 73 | } |
| 74 | if !groupValidation.Ok { |
| 75 | for _, id := range groupValidation.InvalidGroupIds { |
| 76 | validErrs = append(validErrs, codersdk.ValidationError{ |
| 77 | Field: groupsField, |
| 78 | Detail: fmt.Sprintf("group with ID %v does not exist", id), |
| 79 | }) |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | userRoles, usersField := v.Users() |
| 84 | userIDs := make([]uuid.UUID, 0, len(userRoles)) |
| 85 | for idStr, role := range userRoles { |