-
Notifications
You must be signed in to change notification settings - Fork 38
/
customer.go
377 lines (329 loc) · 13.5 KB
/
customer.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
package ghcapi
import (
"bytes"
"database/sql"
"encoding/json"
"io"
"net/http"
"strings"
"github.com/go-openapi/runtime/middleware"
"github.com/gobuffalo/validate/v3"
"github.com/gofrs/uuid"
"github.com/spf13/viper"
"go.uber.org/zap"
"github.com/transcom/mymove/pkg/appcontext"
"github.com/transcom/mymove/pkg/apperror"
"github.com/transcom/mymove/pkg/cli"
customercodeop "github.com/transcom/mymove/pkg/gen/ghcapi/ghcoperations/customer"
"github.com/transcom/mymove/pkg/gen/ghcmessages"
"github.com/transcom/mymove/pkg/handlers"
"github.com/transcom/mymove/pkg/handlers/authentication/okta"
"github.com/transcom/mymove/pkg/handlers/ghcapi/internal/payloads"
"github.com/transcom/mymove/pkg/models"
"github.com/transcom/mymove/pkg/services"
)
func addressModelFromPayload(rawAddress *ghcmessages.Address) *models.Address {
if rawAddress == nil {
return nil
}
return &models.Address{
StreetAddress1: *rawAddress.StreetAddress1,
StreetAddress2: rawAddress.StreetAddress2,
StreetAddress3: rawAddress.StreetAddress3,
City: *rawAddress.City,
State: *rawAddress.State,
PostalCode: *rawAddress.PostalCode,
Country: rawAddress.Country,
}
}
// GetCustomerHandler fetches the information of a specific customer
type GetCustomerHandler struct {
handlers.HandlerConfig
services.CustomerFetcher
}
// Handle getting the information of a specific customer
func (h GetCustomerHandler) Handle(params customercodeop.GetCustomerParams) middleware.Responder {
return h.AuditableAppContextFromRequestWithErrors(params.HTTPRequest,
func(appCtx appcontext.AppContext) (middleware.Responder, error) {
customerID, _ := uuid.FromString(params.CustomerID.String())
customer, err := h.FetchCustomer(appCtx, customerID)
if err != nil {
appCtx.Logger().Error("Loading Customer Info", zap.Error(err))
switch err {
case sql.ErrNoRows:
return customercodeop.NewGetCustomerNotFound(), err
default:
return customercodeop.NewGetCustomerInternalServerError(), err
}
}
customerInfoPayload := payloads.Customer(customer)
return customercodeop.NewGetCustomerOK().WithPayload(customerInfoPayload), nil
})
}
type SearchCustomersHandler struct {
handlers.HandlerConfig
services.CustomerSearcher
}
func (h SearchCustomersHandler) Handle(params customercodeop.SearchCustomersParams) middleware.Responder {
return h.AuditableAppContextFromRequestWithErrors(params.HTTPRequest,
func(appCtx appcontext.AppContext) (middleware.Responder, error) {
searchCustomersParams := services.SearchCustomersParams{
DodID: params.Body.DodID,
CustomerName: params.Body.CustomerName,
Page: params.Body.Page,
PerPage: params.Body.PerPage,
Sort: params.Body.Sort,
Order: params.Body.Order,
}
customers, totalCount, err := h.CustomerSearcher.SearchCustomers(appCtx, &searchCustomersParams)
if err != nil {
appCtx.Logger().Error("Error searching for customer", zap.Error(err))
return customercodeop.NewSearchCustomersInternalServerError(), err
}
searchCustomers := payloads.SearchCustomers(customers)
payload := &ghcmessages.SearchCustomersResult{
Page: 1,
PerPage: 20,
TotalCount: int64(totalCount),
SearchCustomers: *searchCustomers,
}
return customercodeop.NewSearchCustomersOK().WithPayload(payload), nil
})
}
// UpdateCustomerHandler updates a customer via PATCH /customer/{customerId}
type UpdateCustomerHandler struct {
handlers.HandlerConfig
customerUpdater services.CustomerUpdater
}
// Handle updates a customer from a request payload
func (h UpdateCustomerHandler) Handle(params customercodeop.UpdateCustomerParams) middleware.Responder {
return h.AuditableAppContextFromRequestWithErrors(params.HTTPRequest,
func(appCtx appcontext.AppContext) (middleware.Responder, error) {
customerID, err := uuid.FromString(params.CustomerID.String())
if err != nil {
appCtx.Logger().Error("unable to parse customer id param to uuid", zap.Error(err))
return customercodeop.NewUpdateCustomerBadRequest(), err
}
newCustomer := payloads.CustomerToServiceMember(*params.Body)
newCustomer.ID = customerID
updatedCustomer, err := h.customerUpdater.UpdateCustomer(appCtx, params.IfMatch, newCustomer)
if err != nil {
appCtx.Logger().Error("error updating customer", zap.Error(err))
switch err.(type) {
case apperror.NotFoundError:
return customercodeop.NewGetCustomerNotFound(), err
case apperror.InvalidInputError:
payload := payloadForValidationError("Unable to complete request", err.Error(), h.GetTraceIDFromRequest(params.HTTPRequest), validate.NewErrors())
return customercodeop.NewUpdateCustomerUnprocessableEntity().WithPayload(payload), err
case apperror.PreconditionFailedError:
return customercodeop.NewUpdateCustomerPreconditionFailed().WithPayload(&ghcmessages.Error{Message: handlers.FmtString(err.Error())}), err
default:
return customercodeop.NewUpdateCustomerInternalServerError(), err
}
}
customerPayload := payloads.Customer(updatedCustomer)
return customercodeop.NewUpdateCustomerOK().WithPayload(customerPayload), nil
})
}
type CreateCustomerWithOktaOptionHandler struct {
handlers.HandlerConfig
}
// Handle creates a customer/serviceMember from a request payload
func (h CreateCustomerWithOktaOptionHandler) Handle(params customercodeop.CreateCustomerWithOktaOptionParams) middleware.Responder {
return h.AuditableAppContextFromRequestWithErrors(params.HTTPRequest,
func(appCtx appcontext.AppContext) (middleware.Responder, error) {
var err error
var newServiceMember models.ServiceMember
var backupContact models.BackupContact
payload := params.Body
email := payload.PersonalEmail
if email == "" {
badDataError := apperror.NewBadDataError("missing personal email")
payload := payloadForValidationError("Unable to create a customer", badDataError.Error(), h.GetTraceIDFromRequest(params.HTTPRequest), validate.NewErrors())
return customercodeop.NewCreateCustomerWithOktaOptionUnprocessableEntity().WithPayload(payload), badDataError
}
// declaring okta values outside of if statements so we can use them later
var oktaSub string
oktaUser := &models.CreatedOktaUser{}
// if the office user checked "yes", then we will create an okta account for the user
// this will add the user to the okta customer application and send an activation email
if payload.CreateOktaAccount {
var oktaErr error
oktaUser, oktaErr = createOktaProfile(appCtx, params)
if oktaErr != nil {
appCtx.Logger().Error("error creating okta profile", zap.Error(oktaErr))
return customercodeop.NewCreateCustomerWithOktaOptionBadRequest(), oktaErr
}
oktaSub = oktaUser.ID
}
// if the office user checked "no" to indicate the customer does NOT have a CAC, set cac_validated
// to true so that the customer can log in without having to authenticate with a CAC
var cacValidated = false
if !payload.CacUser {
cacValidated = true
}
transactionError := appCtx.NewTransaction(func(_ appcontext.AppContext) error {
var verrs *validate.Errors
// creating a user and populating okta values (for now these can be null)
user, userErr := models.CreateUser(appCtx.DB(), oktaSub, email)
if userErr != nil {
appCtx.Logger().Error("error creating user", zap.Error(err))
return userErr
}
// now we will take all the data we have and build the service member
userID := user.ID
residentialAddress := addressModelFromPayload(&payload.ResidentialAddress.Address)
backupMailingAddress := addressModelFromPayload(&payload.BackupMailingAddress.Address)
var edipi *string
if *payload.Edipi == "" {
edipi = nil
} else {
edipi = payload.Edipi
}
// Create a new serviceMember using the userID
newServiceMember = models.ServiceMember{
UserID: userID,
Edipi: edipi,
Affiliation: (*models.ServiceMemberAffiliation)(payload.Affiliation),
FirstName: &payload.FirstName,
MiddleName: payload.MiddleName,
LastName: &payload.LastName,
Suffix: payload.Suffix,
Telephone: payload.Telephone,
SecondaryTelephone: payload.SecondaryTelephone,
PersonalEmail: &payload.PersonalEmail,
PhoneIsPreferred: &payload.PhoneIsPreferred,
EmailIsPreferred: &payload.EmailIsPreferred,
ResidentialAddress: residentialAddress,
BackupMailingAddress: backupMailingAddress,
CacValidated: cacValidated,
}
// create the service member and save to the db
smVerrs, smErr := models.SaveServiceMember(appCtx, &newServiceMember)
if smVerrs.HasAny() || smErr != nil {
appCtx.Logger().Error("error creating service member", zap.Error(err))
return err
}
// creating backup contact associated with service member since this is done separately
// default permission of EDIT since we want them to be able to change this info
defaultPermission := models.BackupContactPermissionEDIT
backupContact, verrs, err = newServiceMember.CreateBackupContact(appCtx.DB(),
*payload.BackupContact.Name,
*payload.BackupContact.Email,
payload.BackupContact.Phone,
models.BackupContactPermission(defaultPermission))
if err != nil || verrs.HasAny() {
appCtx.Logger().Error("error creating backup contact", zap.Error(err))
return err
}
return nil
})
if transactionError != nil {
return nil, transactionError
}
// covering error returns
if err != nil {
appCtx.Logger().Error("error creating customer", zap.Error(err))
switch err.(type) {
case apperror.NotFoundError:
return customercodeop.NewCreateCustomerWithOktaOptionNotFound(), err
case apperror.InvalidInputError:
payload := payloadForValidationError("Unable to complete request", err.Error(), h.GetTraceIDFromRequest(params.HTTPRequest), validate.NewErrors())
return customercodeop.NewCreateCustomerWithOktaOptionUnprocessableEntity().WithPayload(payload), err
case apperror.PreconditionFailedError:
return customercodeop.NewCreateCustomerWithOktaOptionPreconditionFailed().WithPayload(&ghcmessages.Error{Message: handlers.FmtString(err.Error())}), err
default:
return customercodeop.NewUpdateCustomerInternalServerError(), err
}
}
customerPayload := payloads.CreatedCustomer(&newServiceMember, oktaUser, &backupContact)
return customercodeop.NewCreateCustomerWithOktaOptionOK().WithPayload(customerPayload), nil
})
}
// createOktaProfile sends a request to the Okta Users API
// this creates a user in Okta assigned to the customer group (allowing access to the customer application)
func createOktaProfile(appCtx appcontext.AppContext, params customercodeop.CreateCustomerWithOktaOptionParams) (*models.CreatedOktaUser, error) {
// setting viper so we can access the api key in the env vars
v := viper.New()
v.SetEnvKeyReplacer(strings.NewReplacer("-", "_"))
v.AutomaticEnv()
apiKey := v.GetString(cli.OktaAPIKeyFlag)
customerGroupID := v.GetString(cli.OktaCustomerGroupIDFlag)
// taking all the data that we'll need for the okta profile creation
payload := params.Body
oktaEmail := payload.PersonalEmail
oktaFirstName := payload.FirstName
oktaLastName := payload.LastName
oktaPhone := payload.Telephone
// Creating the Profile struct
profile := models.Profile{
FirstName: oktaFirstName,
LastName: oktaLastName,
Email: oktaEmail,
Login: oktaEmail,
MobilePhone: *oktaPhone,
}
// Creating the OktaUserPayload struct
oktaPayload := models.OktaUserPayload{
Profile: profile,
GroupIds: []string{customerGroupID},
}
// getting okta domain url for request
provider, err := okta.GetOktaProviderForRequest(params.HTTPRequest)
if err != nil {
return nil, err
}
// getting the api call url from provider.go
activate := "true"
baseURL := provider.GetCreateUserURL(activate)
body, err := json.Marshal(oktaPayload)
if err != nil {
appCtx.Logger().Error("error marshaling payload", zap.Error(err))
return nil, err
}
// making HTTP request to Okta Users API to create a user
// this is done via a POST request for creating a user that sends an activation email (when activate=true)
// https://developer.okta.com/docs/reference/api/users/#create-user-without-credentials
req, err := http.NewRequest("POST", baseURL, bytes.NewReader(body))
if err != nil {
appCtx.Logger().Error("could not execute request", zap.Error(err))
return nil, err
}
h := req.Header
h.Add("Authorization", "SSWS "+apiKey)
h.Add("Accept", "application/json")
h.Add("Content-Type", "application/json")
// now let the client send the request
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
appCtx.Logger().Error("could not execute request", zap.Error(err))
return nil, err
}
// if all is well, should have a 200 response
response, err := io.ReadAll(resp.Body)
if err != nil {
appCtx.Logger().Error("could not read response body", zap.Error(err))
return nil, err
}
if resp.StatusCode != http.StatusOK {
if resp.StatusCode == http.StatusInternalServerError {
return nil, err
}
if resp.StatusCode == http.StatusBadRequest {
return nil, err
}
if resp.StatusCode == http.StatusForbidden {
return nil, err
}
}
// now we will take the response and parse it into our Go struct
user := models.CreatedOktaUser{}
err = json.Unmarshal(response, &user)
if err != nil {
appCtx.Logger().Error("could not unmarshal body", zap.Error(err))
return nil, err
}
defer resp.Body.Close()
return &user, nil
}