Skip to content

Commit 0506665

Browse files
akfosterfrostbournesbsaito-sv
authored
Provide customer name and email to Checkout (#131)
* reorganize transaction service; add string-user name to checkout authentication * ID -> Id or id; fix unit21 unit tests; Get Contact by UserId and PlatformId * add GetByUserIdAndPlatformId * fix query; add customer email, and payment IP to checkout auth * Update pkg/model/transaction.go Co-authored-by: Frostbourne <[email protected]> * Update pkg/repository/auth.go Co-authored-by: Frostbourne <[email protected]> * Update pkg/internal/common/receipt.go Co-authored-by: Frostbourne <[email protected]> * Update pkg/service/checkout.go Co-authored-by: Frostbourne <[email protected]> * Update migrations/0003_contact-to-platform_device-to-instrument_tx-leg_transaction.sql Co-authored-by: Frostbourne <[email protected]> * Update pkg/internal/common/sign.go Co-authored-by: Frostbourne <[email protected]> * Update pkg/internal/common/sign.go Co-authored-by: Frostbourne <[email protected]> * Update pkg/repository/device.go Co-authored-by: Frostbourne <[email protected]> * Update pkg/internal/common/receipt.go Co-authored-by: Frostbourne <[email protected]> * Update pkg/internal/common/receipt.go Co-authored-by: Frostbourne <[email protected]> * Update api/middleware/middleware.go * ensure email gets passed * make 'written' ID all caps * Update pkg/repository/auth.go Co-authored-by: saito-sv <[email protected]> * Update pkg/internal/unit21/evaluate_test.go Co-authored-by: saito-sv <[email protected]> --------- Co-authored-by: Frostbourne <[email protected]> Co-authored-by: saito-sv <[email protected]>
1 parent f816b39 commit 0506665

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

51 files changed

+656
-619
lines changed

api/api.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ func StartInternal(config APIConfig) {
6969
func baseMiddleware(logger *zerolog.Logger, e *echo.Echo) {
7070
e.Use(middleware.Tracer())
7171
e.Use(middleware.CORS())
72-
e.Use(middleware.RequestID())
72+
e.Use(middleware.RequestId())
7373
e.Use(middleware.Recover())
7474
e.Use(middleware.Logger(logger))
7575
e.Use(middleware.LogRequest())

api/handler/auth_key.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -61,15 +61,15 @@ func (o authAPIKey) Approve(c echo.Context) error {
6161
return NotAllowedError(c)
6262
}
6363
params := struct {
64-
ID string `param:"id"`
64+
Id string `param:"id"`
6565
}{}
6666
err := c.Bind(&params)
6767

6868
if err != nil {
6969
LogStringError(c, err, "authKey approve: bind")
7070
return echo.NewHTTPError(http.StatusInternalServerError, "Unable to process request")
7171
}
72-
err = o.service.Approve(params.ID)
72+
err = o.service.Approve(params.Id)
7373
if err != nil {
7474
LogStringError(c, err, "authKey approve: approve")
7575
return echo.NewHTTPError(http.StatusInternalServerError, "Unable to process request")

api/handler/login_test.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ func TestStatus200LoginNoncePayload(t *testing.T) {
3030
request := httptest.NewRequest(http.MethodGet, "/?"+q.Encode(), nil)
3131
request.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)
3232

33-
handler := NewLogin(nil, stubs.Auth{})
33+
handler := NewLogin(nil, stubs.Auth{}, stubs.Device{})
3434
handler.RegisterRoutes(e.Group("/login"))
3535
rec := httptest.NewRecorder()
3636
c := e.NewContext(request, rec)
@@ -53,7 +53,7 @@ func TestStatus200LoginVerifySignature(t *testing.T) {
5353
request := httptest.NewRequest(http.MethodPost, "/sign", strings.NewReader(string(jsonBody)))
5454
request.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)
5555

56-
handler := NewLogin(nil, stubs.Auth{})
56+
handler := NewLogin(nil, stubs.Auth{}, stubs.Device{})
5757
handler.RegisterRoutes(e.Group("/login"))
5858
rec := httptest.NewRecorder()
5959
c := e.NewContext(request, rec)
@@ -68,7 +68,7 @@ func TestStatus400MissingWalletLoginNoncePayload(t *testing.T) {
6868
request := httptest.NewRequest(http.MethodGet, "/", nil)
6969
request.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)
7070

71-
handler := NewLogin(nil, stubs.Auth{})
71+
handler := NewLogin(nil, stubs.Auth{}, stubs.Device{})
7272
handler.RegisterRoutes(e.Group("/login"))
7373
rec := httptest.NewRecorder()
7474
c := e.NewContext(request, rec)

api/handler/user.go

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ func (u user) Create(c echo.Context) error {
7272
}
7373

7474
func (u user) Status(c echo.Context) error {
75-
valid, userId := validUserID(IDParam(c), c)
75+
valid, userId := validUserId(IdParam(c), c)
7676
if !valid {
7777
return Unauthorized(c)
7878
}
@@ -92,7 +92,7 @@ func (u user) Update(c echo.Context) error {
9292
LogStringError(c, err, "user: update bind")
9393
return BadRequestError(c)
9494
}
95-
_, userId := validUserID(IDParam(c), c)
95+
_, userId := validUserId(IdParam(c), c)
9696
user, err := u.userService.Update(userId, body)
9797
if err != nil {
9898
LogStringError(c, err, "user: update")
@@ -105,7 +105,7 @@ func (u user) Update(c echo.Context) error {
105105
// VerifyEmail send an email with a link, the user must click on the link for the email to be verified
106106
// the link sent is handled by (verification.VerifyEmail) handler
107107
func (u user) VerifyEmail(c echo.Context) error {
108-
_, userId := validUserID(IDParam(c), c)
108+
_, userId := validUserId(IdParam(c), c)
109109
email := c.QueryParam("email")
110110
if email == "" {
111111
return BadRequestError(c, "Missing or invalid email")
@@ -145,12 +145,12 @@ func (u user) RegisterRoutes(g *echo.Group, ms ...echo.MiddlewareFunc) {
145145
}
146146

147147
// get userId from context and also compare if both are valid
148-
// this is useful for path params validation and userID from JWT
149-
func validUserID(userID string, c echo.Context) (bool, string) {
150-
userId := c.Get("userId").(string)
151-
return userId == userID, userId
148+
// this is useful for path params validation and userId from JWT
149+
func validUserId(userId string, c echo.Context) (bool, string) {
150+
_userId := c.Get("userId").(string)
151+
return _userId == userId, _userId
152152
}
153153

154-
func IDParam(c echo.Context) string {
154+
func IdParam(c echo.Context) string {
155155
return c.Param("id")
156156
}

api/middleware/middleware.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ func LogRequest() echo.MiddlewareFunc {
6565
}
6666

6767
// RequestID generates a unique request ID
68-
func RequestID() echo.MiddlewareFunc {
68+
func RequestId() echo.MiddlewareFunc {
6969
return echoMiddleware.RequestID()
7070
}
7171

pkg/internal/common/cost.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
package common
22

3-
func NativeTokenBuffer(chainID uint64) float64 {
3+
func NativeTokenBuffer(chainId uint64) float64 {
44
return 0.05
55
}
66

7-
func GasBuffer(chainID uint64) float64 {
7+
func GasBuffer(chainId uint64) float64 {
88
return 0.05
99
}
1010

pkg/internal/common/fingerprint.go

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ type FPVisitIpLocation struct {
5454
}
5555

5656
type FPVisitorVisit struct {
57-
RequestID string `json:"requestId"`
57+
RequestId string `json:"requestId"`
5858
Incognito bool `json:"incognito"`
5959
LinkedId string `json:"linkedId"`
6060
Time string `json:"time"`
@@ -66,7 +66,7 @@ type FPVisitorVisit struct {
6666
}
6767

6868
type FPVisitor struct {
69-
ID string `json:"visitorId"`
69+
Id string `json:"visitorId"`
7070
Visits []FPVisitorVisit `json:"visits"`
7171
}
7272

@@ -80,19 +80,19 @@ type HTTPConfig struct {
8080

8181
type FPVisitorOpts struct {
8282
Limit int
83-
RequestID string
84-
LinkedID string
83+
RequestId string
84+
LinkedId string
8585
}
8686

8787
func NewHTTPClient(config HTTPConfig) HTTPClient {
8888
return &http.Client{Timeout: config.Timeout}
8989
}
9090

9191
type FingerprintClient interface {
92-
// GetVisitorByID get the fingerprint visitor by its id
92+
// GetVisitorById get the fingerprint visitor by its id
9393
// it returns the most up to date information for the visitor
9494
// The limit should always be 1 so we can get the latest information
95-
GetVisitorByID(VisitorID string, opts FPVisitorOpts) (FPVisitor, error)
95+
GetVisitorById(VisitorId string, opts FPVisitorOpts) (FPVisitor, error)
9696
Request(method, url string, body io.Reader) (*http.Request, error)
9797
}
9898

@@ -108,9 +108,9 @@ func NewFingerprint(client HTTPClient) FingerprintClient {
108108
return &fingerprint{client: client, apiKey: apiKey, baseURL: baseURL}
109109
}
110110

111-
func (f fingerprint) GetVisitorByID(visitorID string, opts FPVisitorOpts) (FPVisitor, error) {
111+
func (f fingerprint) GetVisitorById(visitorId string, opts FPVisitorOpts) (FPVisitor, error) {
112112
m := FPVisitor{}
113-
r, err := f.Request(http.MethodGet, f.baseURL+"visitors/"+visitorID, nil)
113+
r, err := f.Request(http.MethodGet, f.baseURL+"visitors/"+visitorId, nil)
114114
if err != nil {
115115
return m, err
116116
}
@@ -152,11 +152,11 @@ func (f fingerprint) optionsToQuery(opts FPVisitorOpts) url.Values {
152152
if opts.Limit != 0 {
153153
q.Add("limit", strconv.Itoa(opts.Limit))
154154
}
155-
if opts.RequestID != "" {
156-
q.Add("request_id", opts.RequestID)
155+
if opts.RequestId != "" {
156+
q.Add("request_id", opts.RequestId)
157157
}
158-
if opts.LinkedID != "" {
159-
q.Add("linked_id", opts.LinkedID)
158+
if opts.LinkedId != "" {
159+
q.Add("linked_id", opts.LinkedId)
160160
}
161161
return q
162162
}

pkg/internal/unit21/action.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,9 +32,9 @@ func (a action) Create(
3232
actionData := actionData{
3333
ActionType: instrument.Type,
3434
ActionDetails: actionDetails,
35-
EntityId: instrument.UserID,
35+
EntityId: instrument.UserId,
3636
EntityType: "user",
37-
InstrumentId: instrument.ID,
37+
InstrumentId: instrument.Id,
3838
}
3939

4040
url := "https://" + os.Getenv("UNIT21_ENV") + ".unit21.com/v1/events/create"

pkg/internal/unit21/entity.go

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -35,19 +35,19 @@ func (e entity) Create(user model.User) (unit21Id string, err error) {
3535

3636
// ultimately may want a join here.
3737

38-
communications, err := e.getCommunications(user.ID)
38+
communications, err := e.getCommunications(user.Id)
3939
if err != nil {
4040
log.Err(err).Msg("Failed to gather Unit21 entity communications")
4141
return "", common.StringError(err)
4242
}
4343

44-
digitalData, err := e.getEntityDigitalData(user.ID)
44+
digitalData, err := e.getEntityDigitalData(user.Id)
4545
if err != nil {
4646
log.Err(err).Msg("Failed to gather Unit21 entity digitalData")
4747
return "", common.StringError(err)
4848
}
4949

50-
customData, err := e.getCustomData(user.ID)
50+
customData, err := e.getCustomData(user.Id)
5151
if err != nil {
5252
log.Err(err).Msg("Failed to gather Unit21 entity customData")
5353
return "", common.StringError(err)
@@ -77,29 +77,29 @@ func (e entity) Update(user model.User) (unit21Id string, err error) {
7777

7878
// ultimately may want a join here.
7979

80-
communications, err := e.getCommunications(user.ID)
80+
communications, err := e.getCommunications(user.Id)
8181
if err != nil {
8282
log.Err(err).Msg("Failed to gather Unit21 entity communications")
8383
err = common.StringError(err)
8484
return
8585
}
8686

87-
digitalData, err := e.getEntityDigitalData(user.ID)
87+
digitalData, err := e.getEntityDigitalData(user.Id)
8888
if err != nil {
8989
log.Err(err).Msg("Failed to gather Unit21 entity digitalData")
9090
err = common.StringError(err)
9191
return
9292
}
9393

94-
customData, err := e.getCustomData(user.ID)
94+
customData, err := e.getCustomData(user.Id)
9595
if err != nil {
9696
log.Err(err).Msg("Failed to gather Unit21 entity customData")
9797
err = common.StringError(err)
9898
return
9999
}
100100

101101
orgName := os.Getenv("UNIT21_ORG_NAME")
102-
url := "https://" + os.Getenv("UNIT21_ENV") + ".unit21.com/v1/" + orgName + "/entities/" + user.ID + "/update"
102+
url := "https://" + os.Getenv("UNIT21_ENV") + ".unit21.com/v1/" + orgName + "/entities/" + user.Id + "/update"
103103
body, err := u21Put(url, mapUserToEntity(user, communications, digitalData, customData))
104104

105105
if err != nil {
@@ -182,7 +182,7 @@ func (e entity) getCustomData(userId string) (customData entityCustomData, err e
182182
}
183183

184184
for _, platform := range devices {
185-
customData.Platforms = append(customData.Platforms, platform.PlatformID)
185+
customData.Platforms = append(customData.Platforms, platform.PlatformId)
186186
}
187187
return
188188
}
@@ -197,7 +197,7 @@ func mapUserToEntity(user model.User, communication entityCommunication, digital
197197

198198
jsonBody := &u21Entity{
199199
GeneralData: &entityGeneral{
200-
EntityId: user.ID,
200+
EntityId: user.Id,
201201
EntityType: "user",
202202
Status: user.Status,
203203
RegisteredAt: int(user.CreatedAt.Unix()),

pkg/internal/unit21/entity_test.go

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ func TestUpdateEntity(t *testing.T) {
4141
assert.Greater(t, len([]rune(u21EntityId)), 0)
4242

4343
user := model.User{
44-
ID: entityId,
44+
Id: entityId,
4545
CreatedAt: time.Now(),
4646
UpdatedAt: time.Now(),
4747
DeactivatedAt: nil,
@@ -119,7 +119,7 @@ func TestAddInstruments(t *testing.T) {
119119
func createMockUser(mock sqlmock.Sqlmock, sqlxDB *sqlx.DB) (entityId string, unit21Id string, err error) {
120120
entityId = uuid.NewString()
121121
user := model.User{
122-
ID: entityId,
122+
Id: entityId,
123123
CreatedAt: time.Now(),
124124
UpdatedAt: time.Now(),
125125
DeactivatedAt: nil,
@@ -161,7 +161,7 @@ func createMockInstrumentForUser(userId string, mock sqlmock.Sqlmock, sqlxDB *sq
161161
locationId := uuid.NewString()
162162

163163
instrument = model.Instrument{
164-
ID: instrumentId,
164+
Id: instrumentId,
165165
CreatedAt: time.Now(),
166166
UpdatedAt: time.Now(),
167167
DeactivatedAt: nil,
@@ -171,8 +171,8 @@ func createMockInstrumentForUser(userId string, mock sqlmock.Sqlmock, sqlxDB *sq
171171
Network: "Visa",
172172
PublicKey: "",
173173
Last4: "1234",
174-
UserID: userId,
175-
LocationID: sql.NullString{String: locationId},
174+
UserId: userId,
175+
LocationId: sql.NullString{String: locationId},
176176
}
177177

178178
mockedUserRow1 := sqlmock.NewRows([]string{"id", "type", "status", "tags", "first_name", "middle_name", "last_name"}).
@@ -191,13 +191,15 @@ func createMockInstrumentForUser(userId string, mock sqlmock.Sqlmock, sqlxDB *sq
191191
AddRow(locationId, "Home", "Verified", "20181", "411", "Lark Avenue", "Somerville", "MA", "01443", "USA")
192192
mock.ExpectQuery("SELECT * FROM location WHERE id = $1 AND deactivated_at IS NULL").WithArgs(locationId).WillReturnRows(mockedLocationRow)
193193

194-
repo := InstrumentRepo{
194+
repos := InstrumentRepos{
195195
User: repository.NewUser(sqlxDB),
196196
Device: repository.NewDevice(sqlxDB),
197197
Location: repository.NewLocation(sqlxDB),
198198
}
199199

200-
u21Instrument := NewInstrument(repo)
200+
action := NewAction()
201+
202+
u21Instrument := NewInstrument(repos, action)
201203

202204
u21InstrumentId, err := u21Instrument.Create(instrument)
203205

pkg/internal/unit21/evaluate_test.go

Lines changed: 4 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -66,17 +66,10 @@ func TestEvaluateTransactionManyLinkedCards(t *testing.T) {
6666
assert.NoError(t, err)
6767
assert.Greater(t, len([]rune(u21InstrumentId)), 0)
6868

69-
// Log create instrument action w/ Unit21
70-
u21ActionRepo := ActionRepo{
71-
User: repository.NewUser(sqlxDB),
72-
Device: repository.NewDevice(sqlxDB),
73-
Location: repository.NewLocation(sqlxDB),
74-
}
75-
76-
u21Action := NewAction(u21ActionRepo)
69+
u21Action := NewAction()
7770
_, err = u21Action.Create(instrument, "Creation", u21InstrumentId, "Creation")
7871
if err != nil {
79-
fmt.Printf("Error creating a new instrument action in Unit21")
72+
t.Log("Error creating a new instrument action in Unit21")
8073
return
8174
}
8275
}
@@ -174,13 +167,13 @@ func TestEvaluateTransactionNewUserHighSpend(t *testing.T) {
174167
}
175168

176169
func evaluateMockTransaction(transaction model.Transaction, sqlxDB *sqlx.DB) (pass bool, err error) {
177-
repo := TransactionRepo{
170+
repos := TransactionRepos{
178171
TxLeg: repository.NewTxLeg((sqlxDB)),
179172
User: repository.NewUser(sqlxDB),
180173
Asset: repository.NewAsset(sqlxDB),
181174
}
182175

183-
u21Transaction := NewTransaction(repo)
176+
u21Transaction := NewTransaction(repos)
184177

185178
pass, err = u21Transaction.Evaluate(transaction)
186179

0 commit comments

Comments
 (0)