/
user.go
245 lines (213 loc) · 7.38 KB
/
user.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
package service
import (
"encoding/json"
"errors"
"fmt"
"github.com/esnet/gdg/internal/config"
"github.com/esnet/gdg/internal/service/filters"
"github.com/esnet/gdg/internal/tools"
"github.com/esnet/gdg/internal/types"
"github.com/gosimple/slug"
"github.com/grafana/grafana-openapi-client-go/client/admin_users"
"github.com/grafana/grafana-openapi-client-go/client/users"
"github.com/grafana/grafana-openapi-client-go/models"
"github.com/tidwall/pretty"
"log"
"log/slog"
"path/filepath"
"sort"
"strings"
)
func NewUserFilter(label string) filters.Filter {
filterEntity := filters.NewBaseFilter()
if label == "" {
return filterEntity
}
filterEntity.AddFilter(filters.AuthLabel, label)
filterEntity.AddValidation(filters.DefaultFilter, func(i interface{}) bool {
val, ok := i.(map[filters.FilterType]string)
if !ok {
return ok
}
if filterEntity.GetFilter(filters.AuthLabel) == "" {
return true
}
return val[filters.AuthLabel] == filterEntity.GetFilter(filters.AuthLabel)
})
return filterEntity
}
// GetUserInfo get signed-in user info, requires Basic authentication
func (s *DashNGoImpl) GetUserInfo() (*models.UserProfileDTO, error) {
userInfo, err := s.GetBasicAuthClient().SignedInUser.GetSignedInUser()
if err == nil {
return userInfo.GetPayload(), err
}
return nil, err
}
func (s *DashNGoImpl) DownloadUsers(filter filters.Filter) []string {
var (
userData []byte
err error
)
userListing := s.ListUsers(filter)
var importedUsers []string
userPath := BuildResourceFolder("", config.UserResource)
for ndx, user := range userListing {
if s.isAdminUser(user.ID, user.Name) {
slog.Info("Skipping admin super user")
continue
}
fileName := filepath.Join(userPath, fmt.Sprintf("%s.json", GetSlug(user.Login)))
userData, err = json.Marshal(&userListing[ndx])
if err != nil {
slog.Error("could not serialize user object for userId", "userID", user.ID)
continue
}
if err = s.storage.WriteFile(fileName, pretty.Pretty(userData)); err != nil {
slog.Error("Failed to write file", "filename", user.Login, "err", err)
} else {
importedUsers = append(importedUsers, fileName)
}
}
return importedUsers
}
func (s *DashNGoImpl) isAdminUser(id int64, name string) bool {
return id == 1 || name == "admin"
}
func (s *DashNGoImpl) UploadUsers(filter filters.Filter) []types.UserProfileWithAuth {
filesInDir, err := s.storage.FindAllFiles(config.Config().GetDefaultGrafanaConfig().GetPath(config.UserResource), false)
if err != nil {
slog.Error("failed to list files in directory for userListings", "err", err)
}
var userListings []types.UserProfileWithAuth
var rawUser []byte
userList := s.ListUsers(filter)
var currentUsers = make(map[string]*models.UserSearchHitDTO, 0)
//Build current User Mapping
for ndx, i := range userList {
key := slug.Make(i.Login) + ".json"
currentUsers[key] = userList[ndx]
}
for _, file := range filesInDir {
fileLocation := filepath.Join(config.Config().GetDefaultGrafanaConfig().GetPath(config.UserResource), file)
if strings.HasSuffix(file, ".json") {
if rawUser, err = s.storage.ReadFile(fileLocation); err != nil {
slog.Error("failed to read file", "filename", fileLocation, "err", err)
continue
}
if val, ok := currentUsers[filepath.Base(file)]; ok {
slog.Warn("User already exist, skipping", "username", val.Login)
continue
}
var newUser models.AdminCreateUserForm
//generate user password
password := s.grafanaConf.GetUserSettings().GetPassword(file)
var data = make(map[string]interface{})
if err = json.Unmarshal(rawUser, &data); err != nil {
slog.Error("failed to unmarshall file", "filename", fileLocation, "err", err)
continue
}
data["password"] = password
//Get raw version of payload once more with password
if rawUser, err = json.Marshal(data); err != nil {
slog.Error("failed to marshall file to include password", "filename", fileLocation, "err", err)
}
if err = json.Unmarshal(rawUser, &newUser); err != nil {
slog.Error("failed to unmarshall file", "filename", fileLocation, "err", err)
continue
}
if newUser.Name == "admin" {
slog.Info("Skipping admin user")
continue
}
params := admin_users.NewAdminCreateUserParams()
params.Body = &newUser
userCreated, err := s.GetBasicAuthClient().AdminUsers.AdminCreateUser(&newUser)
if err != nil {
slog.Error("Failed to create user for file", "filename", fileLocation, "err", err)
continue
}
resp, err := s.GetBasicAuthClient().Users.GetUserByID(userCreated.Payload.ID)
if err != nil {
slog.Error("unable to read user back from grafana", "username", newUser.Email, "userID", userCreated.GetPayload().ID)
continue
}
userListings = append(userListings, types.UserProfileWithAuth{UserProfileDTO: *resp.GetPayload(), Password: newUser.Password})
}
}
return userListings
}
// ListUsers list all grafana users
func (s *DashNGoImpl) ListUsers(filter filters.Filter) []*models.UserSearchHitDTO {
if !s.grafanaConf.IsBasicAuth() {
log.Fatal("User listing requires basic auth to be configured. Token based listing is not supported")
}
var filteredUsers []*models.UserSearchHitDTO
params := users.NewSearchUsersParams()
params.Page = tools.PtrOf(int64(1))
params.Perpage = tools.PtrOf(int64(5000))
usersList, err := s.GetClient().Users.SearchUsers(params)
if err != nil {
log.Fatal(err.Error())
}
for _, entry := range usersList.GetPayload() {
if len(entry.AuthLabels) == 0 {
filteredUsers = append(filteredUsers, entry)
} else if filter.ValidateAll(map[filters.FilterType]string{filters.AuthLabel: entry.AuthLabels[0]}) {
filteredUsers = append(filteredUsers, entry)
}
}
sort.Slice(filteredUsers, func(i, j int) bool {
return filteredUsers[i].ID < filteredUsers[j].ID
})
return filteredUsers
}
// DeleteAllUsers remove all users excluding admin or anything matching the filter
func (s *DashNGoImpl) DeleteAllUsers(filter filters.Filter) []string {
userListing := s.ListUsers(filter)
var deletedUsers []string
for _, user := range userListing {
if s.isAdminUser(user.ID, user.Name) {
slog.Info("Skipping admin user")
continue
}
params := admin_users.NewAdminDeleteUserParams()
params.UserID = user.ID
_, err := s.GetBasicAuthClient().AdminUsers.AdminDeleteUser(user.ID)
if err == nil {
deletedUsers = append(deletedUsers, user.Email)
}
}
return deletedUsers
}
// PromoteUser promote the user to have Admin Access
func (s *DashNGoImpl) PromoteUser(userLogin string) (string, error) {
//Get all users
userListing := s.ListUsers(filters.NewBaseFilter())
var user *models.UserSearchHitDTO
for ndx, item := range userListing {
if item.Email == userLogin {
user = userListing[ndx]
break
}
}
if user == nil {
return "", fmt.Errorf("user: '%s' could not be found", userLogin)
}
requestBody := &models.AdminUpdateUserPermissionsForm{IsGrafanaAdmin: true}
msg, err := s.GetBasicAuthClient().AdminUsers.AdminUpdateUserPermissions(user.ID, requestBody)
if err != nil {
errorMsg := fmt.Sprintf("failed to promote user: '%s'", userLogin)
slog.Error("failed to promote user", "username", userLogin, "err", err)
return "", errors.New(errorMsg)
}
return msg.GetPayload().Message, nil
}
// getUserById get the user by ID
func (s *DashNGoImpl) getUserById(userId int64) (*models.UserProfileDTO, error) {
resp, err := s.GetClient().Users.GetUserByID(userId)
if err != nil {
return nil, err
}
return resp.GetPayload(), nil
}