github.com/vmware/govmomi@v0.43.0/simulator/user_directory.go (about) 1 /* 2 Copyright (c) 2017 VMware, Inc. All Rights Reserved. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package simulator 18 19 import ( 20 "strings" 21 22 "github.com/vmware/govmomi/vim25/methods" 23 "github.com/vmware/govmomi/vim25/mo" 24 "github.com/vmware/govmomi/vim25/soap" 25 "github.com/vmware/govmomi/vim25/types" 26 ) 27 28 var DefaultUserGroup = []*types.UserSearchResult{ 29 {FullName: "root", Group: true, Principal: "root"}, 30 {FullName: "root", Group: false, Principal: "root"}, 31 {FullName: "administrator", Group: false, Principal: "admin"}, 32 } 33 34 type UserDirectory struct { 35 mo.UserDirectory 36 37 userGroup []*types.UserSearchResult 38 } 39 40 func (m *UserDirectory) init(*Registry) { 41 m.userGroup = DefaultUserGroup 42 } 43 44 func (u *UserDirectory) RetrieveUserGroups(req *types.RetrieveUserGroups) soap.HasFault { 45 compare := compareFunc(req.SearchStr, req.ExactMatch) 46 47 res := u.search(req.FindUsers, req.FindGroups, compare) 48 49 body := &methods.RetrieveUserGroupsBody{ 50 Res: &types.RetrieveUserGroupsResponse{ 51 Returnval: res, 52 }, 53 } 54 55 return body 56 } 57 58 func (u *UserDirectory) search(findUsers, findGroups bool, compare func(string) bool) (res []types.BaseUserSearchResult) { 59 for _, ug := range u.userGroup { 60 if findUsers && !ug.Group || findGroups && ug.Group { 61 if compare(ug.Principal) { 62 res = append(res, ug) 63 } 64 } 65 } 66 67 return res 68 } 69 70 func (u *UserDirectory) addUser(id string) { 71 u.add(id, false) 72 } 73 74 func (u *UserDirectory) removeUser(id string) { 75 u.remove(id, false) 76 } 77 78 func (u *UserDirectory) add(id string, group bool) { 79 user := &types.UserSearchResult{ 80 FullName: id, 81 Group: group, 82 Principal: id, 83 } 84 85 u.userGroup = append(u.userGroup, user) 86 } 87 88 func (u *UserDirectory) remove(id string, group bool) { 89 for i, ug := range u.userGroup { 90 if ug.Group == group && ug.Principal == id { 91 u.userGroup = append(u.userGroup[:i], u.userGroup[i+1:]...) 92 return 93 } 94 } 95 } 96 97 func compareFunc(compared string, exactly bool) func(string) bool { 98 return func(s string) bool { 99 if exactly { 100 return s == compared 101 } 102 return strings.Contains(strings.ToLower(s), strings.ToLower(compared)) 103 } 104 }