github.com/vmware/govmomi@v0.51.0/simulator/user_directory.go (about) 1 // © Broadcom. All Rights Reserved. 2 // The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. 3 // SPDX-License-Identifier: Apache-2.0 4 5 package simulator 6 7 import ( 8 "strings" 9 10 "github.com/vmware/govmomi/vim25/methods" 11 "github.com/vmware/govmomi/vim25/mo" 12 "github.com/vmware/govmomi/vim25/soap" 13 "github.com/vmware/govmomi/vim25/types" 14 ) 15 16 var DefaultUserGroup = []*types.UserSearchResult{ 17 {FullName: "root", Group: true, Principal: "root"}, 18 {FullName: "root", Group: false, Principal: "root"}, 19 {FullName: "administrator", Group: false, Principal: "admin"}, 20 } 21 22 type UserDirectory struct { 23 mo.UserDirectory 24 25 userGroup []*types.UserSearchResult 26 } 27 28 func (m *UserDirectory) init(*Registry) { 29 m.userGroup = DefaultUserGroup 30 } 31 32 func (u *UserDirectory) RetrieveUserGroups(req *types.RetrieveUserGroups) soap.HasFault { 33 compare := compareFunc(req.SearchStr, req.ExactMatch) 34 35 res := u.search(req.FindUsers, req.FindGroups, compare) 36 37 body := &methods.RetrieveUserGroupsBody{ 38 Res: &types.RetrieveUserGroupsResponse{ 39 Returnval: res, 40 }, 41 } 42 43 return body 44 } 45 46 func (u *UserDirectory) search(findUsers, findGroups bool, compare func(string) bool) (res []types.BaseUserSearchResult) { 47 for _, ug := range u.userGroup { 48 if findUsers && !ug.Group || findGroups && ug.Group { 49 if compare(ug.Principal) { 50 res = append(res, ug) 51 } 52 } 53 } 54 55 return res 56 } 57 58 func (u *UserDirectory) addUser(id string) { 59 u.add(id, false) 60 } 61 62 func (u *UserDirectory) removeUser(id string) { 63 u.remove(id, false) 64 } 65 66 func (u *UserDirectory) add(id string, group bool) { 67 user := &types.UserSearchResult{ 68 FullName: id, 69 Group: group, 70 Principal: id, 71 } 72 73 u.userGroup = append(u.userGroup, user) 74 } 75 76 func (u *UserDirectory) remove(id string, group bool) { 77 for i, ug := range u.userGroup { 78 if ug.Group == group && ug.Principal == id { 79 u.userGroup = append(u.userGroup[:i], u.userGroup[i+1:]...) 80 return 81 } 82 } 83 } 84 85 func compareFunc(compared string, exactly bool) func(string) bool { 86 return func(s string) bool { 87 if exactly { 88 return s == compared 89 } 90 return strings.Contains(strings.ToLower(s), strings.ToLower(compared)) 91 } 92 }