forked from Telmate/proxmox-api-go
/
config_group.go
412 lines (383 loc) · 11.1 KB
/
config_group.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
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
package proxmox
import (
"encoding/json"
"errors"
"fmt"
"regexp"
"strings"
)
type ConfigGroup struct {
Name GroupName `json:"name"`
Comment string `json:"comment,omitempty"`
// Setting the Members will update the group membership to only include the specified members.
Members *[]UserID `json:"members,omitempty"`
}
// Creates the specified group
func (config *ConfigGroup) Create(client *Client) error {
config.Validate(true)
params := config.mapToApiValues(true)
err := client.Post(params, "/access/groups")
if err != nil {
params, _ := json.Marshal(¶ms)
return fmt.Errorf("error creating Group: %v, (params: %v)", err, string(params))
}
if config.Members != nil {
return config.Name.SetMembers(config.Members, client)
}
return nil
}
// Maps the struct to the API values proxmox understands
func (config *ConfigGroup) mapToApiValues(create bool) (params map[string]interface{}) {
params = map[string]interface{}{
"comment": config.Comment,
}
if create {
params["groupid"] = string(config.Name)
}
return
}
func (config ConfigGroup) mapToStruct(params map[string]interface{}) *ConfigGroup {
if _, isSet := params["groupid"]; isSet {
config.Name = GroupName(params["groupid"].(string))
}
if _, isSet := params["comment"]; isSet {
config.Comment = params["comment"].(string)
}
if _, isSet := params["members"]; isSet {
config.Members = UserID{}.mapToArray(params["members"].([]interface{}))
}
return &config
}
// Custom error for when the *ConfigGroup is nil
func (config *ConfigGroup) nilCheck() error {
if config == nil {
return errors.New("pointer for (ConfigGroup) is nil")
}
return nil
}
// Created or updates the specified group
func (config *ConfigGroup) Set(client *Client) (err error) {
err = config.nilCheck()
if err != nil {
return
}
existence, err := config.Name.CheckExistence(client)
if err != nil {
return
}
if existence {
return config.Update(client)
}
return config.Create(client)
}
// Updates the specified group
func (config *ConfigGroup) Update(client *Client) error {
config.Validate(false)
params := config.mapToApiValues(true)
err := client.Put(params, "/access/groups/"+string(config.Name))
if err != nil {
params, _ := json.Marshal(¶ms)
return fmt.Errorf("error updating Group: %v, (params: %v)", err, string(params))
}
if config.Members != nil {
return config.Name.SetMembers(config.Members, client)
}
return nil
}
// Validates all items and sub items of the ConfigGroup
func (config *ConfigGroup) Validate(create bool) (err error) {
err = config.nilCheck()
if err != nil {
return
}
if create {
err = config.Name.Validate()
}
if config.Members != nil {
for _, e := range *config.Members {
err = e.Validate()
if err != nil {
return
}
}
}
return
}
// GroupName may only contain the following characters: abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-_
type GroupName string
// Add users to the specified group
func (group GroupName) AddUsersToGroup(members *[]UserID, client *Client) error {
users, err := listUsersFull(client)
if err != nil {
return err
}
return configUserShort{}.updateUsersMembership(group.usersToAddToGroup(users, members), client)
}
// Convert a array of GroupName to a comma separated string
func (GroupName) arrayToCsv(groupList *[]GroupName) (groups string) {
if groupList == nil {
return
}
switch len(*groupList) {
case 0:
return
case 1:
return string((*groupList)[0])
}
for i, e := range *groupList {
if i > 0 {
groups = groups + ","
}
groups = groups + string(e)
}
return
}
// Check if the specified group exists.
func (group GroupName) CheckExistence(client *Client) (bool, error) {
err := group.Validate()
if err != nil {
return false, nil
}
paramArray, err := listGroups(client)
if err != nil {
return false, nil
}
return ItemInKeyOfArray(paramArray, "groupid", string(group)), nil
}
// Convert a comma separated string to an array of GroupName
func (GroupName) csvToArray(csv string) []GroupName {
if csv == "" {
return []GroupName{}
}
tmpArray := strings.Split(csv, ",")
groups := make([]GroupName, len(tmpArray))
for i := range tmpArray {
groups[i] = GroupName(tmpArray[i])
}
return groups
}
// Deletes the specified group
func (group GroupName) Delete(client *Client) (err error) {
err = group.Validate()
if err != nil {
return
}
return client.Delete("/access/groups/" + string(group))
}
func (group GroupName) inArray(groups []GroupName) bool {
if group == "" || groups == nil {
return false
}
for _, e := range groups {
if e == group {
return true
}
}
return false
}
// params can only be of type []interface{} or string
func (GroupName) mapToArray(params any) *[]GroupName {
groupList := []GroupName{}
switch tmpParams := params.(type) {
case []interface{}:
groups := ArrayToStringType(tmpParams)
if len(groups) == 1 {
if groups[0] == "" {
return &groupList
}
}
groupList = make([]GroupName, len(groups))
for i := range groups {
groupList[i] = GroupName(groups[i])
}
case string:
groupList = GroupName("").csvToArray(tmpParams)
}
return &groupList
}
// Recursively remove all users from the specified group
func (group GroupName) RemoveAllUsersFromGroup(client *Client) (err error) {
users, err := listUsersFull(client)
if err != nil {
return
}
return configUserShort{}.updateUsersMembership(group.removeAllUsersFromGroup(users), client)
}
// Generate a array of users with their updated group memberships.
// This list only includes users who where a member of the specified GroupName.
func (group GroupName) removeAllUsersFromGroup(allUsers []interface{}) *[]configUserShort {
usersToUpdate := []configUserShort{}
for _, e := range allUsers {
params := e.(map[string]interface{})
if _, isSet := params["userid"]; !isSet {
continue
}
if _, isSet := params["groups"]; !isSet {
continue
}
groups := GroupName("").csvToArray(params["groups"].(string))
if group.inArray(groups) {
groups = group.removeFromArray(groups)
usersToUpdate = append(usersToUpdate, configUserShort{User: UserID{}.mapToStruct(params["userid"].(string)), Groups: &groups})
}
}
return &usersToUpdate
}
func (group GroupName) removeAllUsersFromGroupExcept(allUsers []interface{}, members *[]UserID) *[]configUserShort {
if group == "" {
return nil
}
if members == nil {
return group.removeAllUsersFromGroup(allUsers)
}
if len(*members) == 0 {
return group.removeAllUsersFromGroup(allUsers)
}
usersToUpdate := []configUserShort{}
for _, e := range allUsers {
params := e.(map[string]interface{})
if _, isSet := params["userid"]; !isSet {
continue
}
var userInMembers bool
for _, ee := range *members {
if params["userid"] == ee.ToString() {
userInMembers = true
break
}
}
if !userInMembers {
var groups []GroupName
if _, isSet := params["groups"]; isSet {
groups = GroupName("").csvToArray(params["groups"].(string))
}
if group.inArray(groups) {
groups = group.removeFromArray(groups)
usersToUpdate = append(usersToUpdate, configUserShort{User: UserID{}.mapToStruct(params["userid"].(string)), Groups: &groups})
}
}
}
return &usersToUpdate
}
// Remove the specified GroupName from the array of GroupName
func (group GroupName) removeFromArray(groups []GroupName) []GroupName {
newGroups := []GroupName{}
for _, e := range groups {
if e != group {
newGroups = append(newGroups, e)
}
}
return newGroups
}
// Remove users from the specified group
func (group GroupName) RemoveUsersFromGroup(members *[]UserID, client *Client) (err error) {
users, err := listUsersFull(client)
if err != nil {
return err
}
return configUserShort{}.updateUsersMembership(group.usersToRemoveFromGroup(users, members), client)
}
// Recursively add and remove users from the specified group so only the the specified users will be members of the group
func (group GroupName) SetMembers(members *[]UserID, client *Client) (err error) {
users, err := listUsersFull(client)
if err != nil {
return
}
err = configUserShort{}.updateUsersMembership(group.removeAllUsersFromGroupExcept(users, members), client)
if err != nil {
return
}
return configUserShort{}.updateUsersMembership(group.usersToAddToGroup(users, members), client)
}
func (group GroupName) usersToAddToGroup(allUsers []interface{}, members *[]UserID) *[]configUserShort {
if group == "" || members == nil {
return nil
}
usersToUpdate := []configUserShort{}
for _, e := range allUsers {
params := e.(map[string]interface{})
if _, isSet := params["userid"]; !isSet {
continue
}
for ii, ee := range *members {
if params["userid"] == ee.ToString() {
var groups []GroupName
if _, isSet := params["groups"]; isSet {
groups = GroupName("").csvToArray(params["groups"].(string))
}
if !group.inArray(groups) {
groups = append(groups, group)
usersToUpdate = append(usersToUpdate, configUserShort{User: (*members)[ii], Groups: &groups})
}
}
}
}
return &usersToUpdate
}
func (group GroupName) usersToRemoveFromGroup(allUsers []interface{}, members *[]UserID) *[]configUserShort {
if group == "" || members == nil {
return nil
}
usersToUpdate := []configUserShort{}
for _, e := range allUsers {
params := e.(map[string]interface{})
if _, isSet := params["userid"]; !isSet {
continue
}
for ii, ee := range *members {
if params["userid"] == ee.ToString() {
var groups []GroupName
if _, isSet := params["groups"]; isSet {
groups = GroupName("").csvToArray(params["groups"].(string))
}
if group.inArray(groups) {
groups = group.removeFromArray(groups)
usersToUpdate = append(usersToUpdate, configUserShort{User: (*members)[ii], Groups: &groups})
}
}
}
}
return &usersToUpdate
}
// Check if a groupname is valid.
func (group GroupName) Validate() error {
if group == "" {
return errors.New("variable of type (GroupName) may not be empty")
}
// proxmox does not seem to enforce any limit on the length of a group name. When going over thousands of charters the ui kinda breaks.
if len([]rune(group)) > 1000 {
return errors.New("variable of type (GroupName) may not be more tha 1000 characters long")
}
regex, _ := regexp.Compile(`^([a-z]|[A-Z]|[0-9]|_|-)*$`)
if regex.Match([]byte(group)) {
return nil
}
return errors.New("")
}
// Returns a list of all existing groups
func ListGroups(client *Client) (*[]ConfigGroup, error) {
paramArray, err := listGroups(client)
if err != nil {
return nil, err
}
groups := make([]ConfigGroup, len(paramArray))
for i, e := range paramArray {
groups[i] = *ConfigGroup{}.mapToStruct(e.(map[string]interface{}))
}
return &groups, nil
}
// list all groups directly from the api without any extra formatting
func listGroups(client *Client) ([]interface{}, error) {
return client.GetItemListInterfaceArray("/access/groups")
}
func NewConfigGroupFromApi(groupId GroupName, client *Client) (*ConfigGroup, error) {
err := groupId.Validate()
if err != nil {
return nil, err
}
config, err := client.GetItemConfigMapStringInterface("/access/groups/"+string(groupId), "group", "CONFIG")
if err != nil {
return nil, err
}
return ConfigGroup{Name: groupId}.mapToStruct(config), nil
}