/
client.go
409 lines (359 loc) · 10.9 KB
/
client.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
// Copyright The Linux Foundation and each contributor to CommunityBridge.
// SPDX-License-Identifier: MIT
package user_service
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strings"
"github.com/communitybridge/easycla/cla-backend-go/utils"
"github.com/sirupsen/logrus"
log "github.com/communitybridge/easycla/cla-backend-go/logging"
"github.com/communitybridge/easycla/cla-backend-go/v2/user-service/client/staff"
"github.com/aws/aws-sdk-go/aws"
"github.com/communitybridge/easycla/cla-backend-go/token"
"github.com/communitybridge/easycla/cla-backend-go/v2/user-service/client"
"github.com/communitybridge/easycla/cla-backend-go/v2/user-service/client/bulk"
"github.com/communitybridge/easycla/cla-backend-go/v2/user-service/client/user"
"github.com/communitybridge/easycla/cla-backend-go/v2/user-service/models"
runtimeClient "github.com/go-openapi/runtime/client"
"github.com/go-openapi/strfmt"
)
var (
// ErrUserNotFound is an error for users not found
ErrUserNotFound = errors.New("user not found")
)
// Client is client for user_service
type Client struct {
cl *client.UserServiceAPI
apiKey string
apiGwURL string
}
var (
userServiceClient *Client
)
// InitClient initializes the user_service client
func InitClient(APIGwURL string, apiKey string) {
APIGwURL = strings.ReplaceAll(APIGwURL, "https://", "")
userServiceClient = &Client{
apiKey: apiKey,
apiGwURL: APIGwURL,
cl: client.NewHTTPClientWithConfig(strfmt.Default, &client.TransportConfig{
Host: APIGwURL,
BasePath: "user-service/v1",
Schemes: []string{"https"},
}),
}
}
// GetClient return user_service client
func GetClient() *Client {
return userServiceClient
}
// GetUsersByUsernames search users by lf username
func (usc *Client) GetUsersByUsernames(lfUsernames []string) ([]*models.User, error) {
f := logrus.Fields{
"functionName": "GetUsersByUsernames",
"lfUsernames": strings.Join(lfUsernames, ","),
}
tok, err := token.GetToken()
if err != nil {
log.WithFields(f).WithError(err).Warn("problem obtaining token")
return nil, err
}
params := bulk.NewSearchBulkParams()
params.SearchBulk = &models.SearchBulk{
List: lfUsernames,
Type: aws.String("username"),
}
clientAuth := runtimeClient.BearerToken(tok)
result, err := usc.cl.Bulk.SearchBulk(params, clientAuth)
if err != nil {
log.WithFields(f).WithError(err).Warn("problem with the bulk search")
return nil, err
}
return result.Payload.Data, nil
}
// GetUserByUsername returns user by lfUsername
func (usc *Client) GetUserByUsername(lfUsername string) (*models.User, error) {
f := logrus.Fields{
"functionName": "GetUserByUsername",
"lfUsername": lfUsername,
}
// use the ListUsers API endpoint (actually called FindUsers) with the lfUsername filter
userModel, err := usc.ListUsersByUsername(lfUsername)
if err != nil {
log.WithFields(f).WithError(err).Warn("problem loading user by username")
return nil, err
}
if userModel == nil {
log.WithFields(f).Debug("get by username returned no results")
return nil, ErrUserNotFound
}
return userModel, nil
}
// SearchUsers returns a single user based on firstName, lastName and email parameters
func (usc *Client) SearchUsers(firstName string, lastName string, email string) (*models.User, error) {
f := logrus.Fields{
"functionName": "SearchUsers",
"firstName": firstName,
"lastName": lastName,
"email": email,
}
// TODO: DAD - let's replace this with the client sub implementation rather than a manual HTTP request
query := fmt.Sprintf("email=%s&firstname=%s&lastname=%s", email, firstName, lastName)
url := fmt.Sprintf("https://%s/user-service/v1/users/search?%s", usc.apiGwURL, query)
tok, err := token.GetToken()
if err != nil {
log.WithFields(f).WithError(err).Warn("problem searching user")
return nil, err
}
log.WithFields(f).Debug("searching for user...")
request, err := http.NewRequest("GET", url, nil)
if err != nil {
log.WithFields(f).WithError(err).Warn("problem building new request")
return nil, err
}
request.Header.Set("X-API-KEY", usc.apiKey)
request.Header.Set("Authorization", "Bearer "+tok)
request.Header.Set("Content-Type", "application/json")
response, err := http.DefaultClient.Do(request)
if err != nil {
log.WithFields(f).WithError(err).Warn("problem searching user")
return nil, err
}
defer func() {
closeErr := response.Body.Close()
if closeErr != nil {
log.WithFields(f).WithError(closeErr).Warn("error closing body")
}
}()
data, err := io.ReadAll(response.Body)
if err != nil {
log.WithFields(f).WithError(err).Warn("problem decoding the user response")
return nil, err
}
userList, err := getUsers(data)
if err != nil {
log.WithFields(f).WithError(err).Warn("problem processing the user response")
return nil, err
}
for _, userItem := range userList {
for _, userEmail := range userItem.Emails {
if *userEmail.EmailAddress == email {
if userItem.FirstName == firstName && userItem.LastName == lastName {
return userItem, nil
}
}
}
}
return nil, errors.New("user not found")
}
// ListUsersByUsername returns the username
func (usc *Client) ListUsersByUsername(lfUsername string) (*models.User, error) {
f := logrus.Fields{
"functionName": "ListUsersByUsername",
"lfUsername": lfUsername,
}
tok, err := token.GetToken()
if err != nil {
log.WithFields(f).WithError(err).Warn("problem obtaining token")
return nil, err
}
clientAuth := runtimeClient.BearerToken(tok)
params := &user.FindUsersParams{
Username: &lfUsername,
Context: utils.NewContext(),
}
result, err := usc.cl.User.FindUsers(params, clientAuth)
if err != nil {
log.WithFields(f).WithError(err).Warn("problem finding user by lfUsername")
return nil, err
}
users := result.Payload.Data
if len(users) == 0 {
log.WithFields(f).Debug("get by lfUsername returned no results")
return nil, ErrUserNotFound
}
return users[0], nil
}
// SearchUsersByEmail returns a single user based on the email parameter
func (usc *Client) SearchUsersByEmail(email string) (*models.User, error) {
f := logrus.Fields{
"functionName": "SearchUsersByEmail",
"email": email,
}
tok, err := token.GetToken()
if err != nil {
log.WithFields(f).WithError(err).Warn("problem obtaining token")
return nil, err
}
clientAuth := runtimeClient.BearerToken(tok)
params := &user.FindUsersParams{
Email: &email,
Context: context.Background(),
}
result, err := usc.cl.User.FindUsers(params, clientAuth)
if err != nil {
log.WithFields(f).WithError(err).Warn("problem finding user by email")
return nil, err
}
users := result.Payload.Data
if len(users) == 0 {
log.WithFields(f).Debug("get by lfUsername returned no results")
return nil, ErrUserNotFound
}
return users[0], nil
}
func getUsers(body []byte) ([]*models.User, error) {
var users = new(models.UserList)
err := json.Unmarshal(body, &users)
if err != nil {
return nil, err
}
return users.Data, err
}
// SearchUserByEmail search user by email
func (usc *Client) SearchUserByEmail(email string) (*models.User, error) {
f := logrus.Fields{
"functionName": "SearchUserByEmail",
"email": email,
}
params := &user.SearchUsersParams{
Email: &email,
Context: context.Background(),
}
tok, err := token.GetToken()
if err != nil {
log.WithFields(f).WithError(err).Warn("problem obtaining token")
return nil, err
}
clientAuth := runtimeClient.BearerToken(tok)
result, err := usc.cl.User.SearchUsers(params, clientAuth)
if err != nil {
log.WithFields(f).WithError(err).Warn("problem finding user by email")
return nil, err
}
users := result.Payload.Data
if len(users) == 0 {
log.WithFields(f).Debug("get by lfUsername returned no results")
return nil, ErrUserNotFound
}
return users[0], nil
}
// ConvertToContact converts user to contact from lead
func (usc *Client) ConvertToContact(userSFID string) error {
params := &user.ConvertToContactParams{
SalesforceID: userSFID,
Context: context.Background(),
}
tok, err := token.GetToken()
if err != nil {
return err
}
clientAuth := runtimeClient.BearerToken(tok)
_, _, err = usc.cl.User.ConvertToContact(params, clientAuth) //nolint
if err != nil {
return err
}
return nil
}
// GetUser returns user from user-service
func (usc *Client) GetUser(userSFID string) (*models.User, error) {
params := &user.GetUserParams{
SalesforceID: userSFID,
Context: context.Background(),
}
tok, err := token.GetToken()
if err != nil {
return nil, err
}
clientAuth := runtimeClient.BearerToken(tok)
result, err := usc.cl.User.GetUser(params, clientAuth)
if err != nil {
return nil, err
}
return result.Payload, nil
}
// GetStaff returns staff details from user-service
func (usc *Client) GetStaff(userSFID string) (*models.Staff, error) {
params := &staff.GetStaffParams{
SalesforceID: userSFID,
Context: context.Background(),
}
tok, err := token.GetToken()
if err != nil {
return nil, err
}
clientAuth := runtimeClient.BearerToken(tok)
result, err := usc.cl.Staff.GetStaff(params, clientAuth)
if err != nil {
return nil, err
}
return result.Payload, nil
}
// GetUserEmail returns email of a user given username
func (usc *Client) GetUserEmail(username string) (string, error) {
user, err := usc.GetUserByUsername(username)
if err != nil {
return "", err
}
if user != nil && len(user.Emails) > 0 {
return *user.Emails[0].EmailAddress, nil
}
return "", nil
}
// UpdateUserAccount updates users org
func (usc *Client) UpdateUserAccount(userSFID string, orgID string) error {
f := logrus.Fields{
"functionName": "UpdateUserAccount",
"organizationID": orgID,
"userSFID": userSFID,
}
tok, err := token.GetToken()
if err != nil {
log.WithFields(f).WithError(err).Warn("problem obtaining token")
return err
}
clientAuth := runtimeClient.BearerToken(tok)
params := &user.UpdatePartialUserParams{
SalesforceID: userSFID,
UpdatePartialUser: &models.UpdatePartialUser{
AccountID: &orgID,
},
Context: context.Background(),
}
result, updateErr := usc.cl.User.UpdatePartialUser(params, clientAuth)
if updateErr != nil {
log.WithFields(f).WithError(updateErr).Warn("problem updating user")
return updateErr
}
log.WithFields(f).Debugf("successfully updated user: %s", result)
return nil
}
// GetPrimaryEmail gets user primary email
func (usc *Client) GetPrimaryEmail(user *models.User) string {
f := logrus.Fields{
"functionName": "GetPrimaryEmail",
}
primaryEmail := ""
for _, email := range user.Emails {
if *email.IsPrimary {
log.WithFields(f).Debugf("Found primary email : %s ", *email.EmailAddress)
primaryEmail = *email.EmailAddress
}
}
return primaryEmail
}
// EmailsToSlice converts a user model's email addresses to a string slice
func (usc *Client) EmailsToSlice(user *models.User) []string {
var emailList []string
for _, email := range user.Emails {
if email.EmailAddress != nil {
emailList = append(emailList, *email.EmailAddress)
}
}
return emailList
}