-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathserver.go
741 lines (644 loc) · 24.7 KB
/
server.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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
package user
import (
"context"
"database/sql"
"time"
"github.com/mr-tron/base58/base58"
"github.com/sirupsen/logrus"
"golang.org/x/text/language"
xrate "golang.org/x/time/rate"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
commonpb "github.com/code-payments/code-protobuf-api/generated/go/common/v1"
messagingpb "github.com/code-payments/code-protobuf-api/generated/go/messaging/v1"
transactionpb "github.com/code-payments/code-protobuf-api/generated/go/transaction/v2"
userpb "github.com/code-payments/code-protobuf-api/generated/go/user/v1"
"github.com/code-payments/code-server/pkg/code/antispam"
auth_util "github.com/code-payments/code-server/pkg/code/auth"
"github.com/code-payments/code-server/pkg/code/common"
code_data "github.com/code-payments/code-server/pkg/code/data"
"github.com/code-payments/code-server/pkg/code/data/account"
"github.com/code-payments/code-server/pkg/code/data/intent"
"github.com/code-payments/code-server/pkg/code/data/paymentrequest"
"github.com/code-payments/code-server/pkg/code/data/phone"
"github.com/code-payments/code-server/pkg/code/data/preferences"
"github.com/code-payments/code-server/pkg/code/data/twitter"
"github.com/code-payments/code-server/pkg/code/data/user"
"github.com/code-payments/code-server/pkg/code/data/user/identity"
"github.com/code-payments/code-server/pkg/code/data/user/storage"
"github.com/code-payments/code-server/pkg/code/data/webhook"
"github.com/code-payments/code-server/pkg/code/server/grpc/messaging"
transaction_server "github.com/code-payments/code-server/pkg/code/server/grpc/transaction/v2"
"github.com/code-payments/code-server/pkg/code/thirdparty"
"github.com/code-payments/code-server/pkg/grpc/client"
"github.com/code-payments/code-server/pkg/pointer"
"github.com/code-payments/code-server/pkg/rate"
"github.com/code-payments/code-server/pkg/sync"
)
type identityServer struct {
log *logrus.Entry
conf *conf
data code_data.Provider
auth *auth_util.RPCSignatureVerifier
limiter *limiter
antispamGuard *antispam.Guard
messagingClient messaging.InternalMessageClient
domainVerifier thirdparty.DomainVerifier
// todo: distributed lock
intentLocks *sync.StripedLock
userpb.UnimplementedIdentityServer
}
func NewIdentityServer(
data code_data.Provider,
auth *auth_util.RPCSignatureVerifier,
antispamGuard *antispam.Guard,
messagingClient messaging.InternalMessageClient,
configProvider ConfigProvider,
) userpb.IdentityServer {
// todo: don't use a local rate limiter, but it's good enough for now
// todo: these rate limits are arbitrary and might need tuning
limiter := newLimiter(func(r float64) rate.Limiter {
return rate.NewLocalRateLimiter(xrate.Limit(r))
}, 1, 5)
return &identityServer{
log: logrus.StandardLogger().WithField("type", "user/server"),
conf: configProvider(),
data: data,
auth: auth,
limiter: limiter,
antispamGuard: antispamGuard,
messagingClient: messagingClient,
domainVerifier: thirdparty.VerifyDomainNameOwnership,
intentLocks: sync.NewStripedLock(1024),
}
}
func (s *identityServer) LinkAccount(ctx context.Context, req *userpb.LinkAccountRequest) (*userpb.LinkAccountResponse, error) {
log := s.log.WithField("method", "LinkAccount")
log = client.InjectLoggingMetadata(ctx, log)
ownerAccount, err := common.NewAccountFromProto(req.OwnerAccountId)
if err != nil {
log.WithError(err).Warn("owner account is invalid")
return nil, status.Error(codes.Internal, "")
}
log = log.WithField("owner_account", ownerAccount.PublicKey().ToBase58())
signature := req.Signature
req.Signature = nil
if err := s.auth.Authenticate(ctx, ownerAccount, req, signature); err != nil {
return nil, err
}
var result userpb.LinkAccountResponse_Result
var userID *user.UserID
var dataContainerID *user.DataContainerID
var metadata *userpb.PhoneMetadata
switch token := req.Token.(type) {
case *userpb.LinkAccountRequest_Phone:
log = log.WithFields(logrus.Fields{
"phone": token.Phone.PhoneNumber.Value,
"code": token.Phone.Code.Value,
})
if !s.limiter.allowPhoneLinking(ctx, token.Phone.PhoneNumber.Value) {
result = userpb.LinkAccountResponse_RATE_LIMITED
break
}
allow, err := s.antispamGuard.AllowLinkAccount(ctx, ownerAccount, token.Phone.PhoneNumber.Value)
if err != nil {
log.WithError(err).Warn("failure performing antispam checks")
return nil, status.Error(codes.Internal, "")
} else if !allow {
result = userpb.LinkAccountResponse_RATE_LIMITED
break
}
err = s.data.UsePhoneLinkingToken(ctx, token.Phone.PhoneNumber.Value, token.Phone.Code.Value)
if err == phone.ErrLinkingTokenNotFound {
result = userpb.LinkAccountResponse_INVALID_TOKEN
break
} else if err != nil {
log.WithError(err).Warn("failure using phone linking token")
return nil, status.Error(codes.Internal, "")
}
falseValue := false
err = s.data.SaveOwnerAccountPhoneSetting(ctx, token.Phone.PhoneNumber.Value, &phone.OwnerAccountSetting{
OwnerAccount: ownerAccount.PublicKey().ToBase58(),
IsUnlinked: &falseValue,
CreatedAt: time.Now(),
LastUpdatedAt: time.Now(),
})
if err != nil {
log.WithError(err).Warn("failure enabling remote send setting")
return nil, status.Error(codes.Internal, "")
}
err = s.data.SavePhoneVerification(ctx, &phone.Verification{
PhoneNumber: token.Phone.PhoneNumber.Value,
OwnerAccount: ownerAccount.PublicKey().ToBase58(),
CreatedAt: time.Now(),
LastVerifiedAt: time.Now(),
})
if err != nil {
log.WithError(err).Warn("failure saving verification record")
return nil, status.Error(codes.Internal, "")
}
newUser := identity.Record{
ID: user.NewUserID(),
View: &user.View{
PhoneNumber: &token.Phone.PhoneNumber.Value,
},
CreatedAt: time.Now(),
}
err = s.data.PutUser(ctx, &newUser)
if err != identity.ErrAlreadyExists && err != nil {
log.WithError(err).Warn("failure inserting user identity")
return nil, status.Error(codes.Internal, "")
}
newDataContainer := &storage.Record{
ID: user.NewDataContainerID(),
OwnerAccount: ownerAccount.PublicKey().ToBase58(),
IdentifyingFeatures: &user.IdentifyingFeatures{
PhoneNumber: &token.Phone.PhoneNumber.Value,
},
CreatedAt: time.Now(),
}
err = s.data.PutUserDataContainer(ctx, newDataContainer)
if err != storage.ErrAlreadyExists && err != nil {
log.WithError(err).Warn("failure inserting data container")
return nil, status.Error(codes.Internal, "")
}
existingUser, err := s.data.GetUserByPhoneView(ctx, token.Phone.PhoneNumber.Value)
if err != nil {
log.WithError(err).Warn("failure getting user identity from phone view")
return nil, status.Error(codes.Internal, "")
}
userID = existingUser.ID
log = log.WithField("user", userID.String())
existingDataContainer, err := s.data.GetUserDataContainerByPhone(ctx, ownerAccount.PublicKey().ToBase58(), token.Phone.PhoneNumber.Value)
if err != nil {
log.WithError(err).Warn("failure getting data container for phone")
return nil, status.Error(codes.Internal, "")
}
dataContainerID = existingDataContainer.ID
metadata = &userpb.PhoneMetadata{
IsLinked: true,
}
default:
return nil, status.Error(codes.InvalidArgument, "token must be set")
}
if result != userpb.LinkAccountResponse_OK {
return &userpb.LinkAccountResponse{
Result: result,
}, nil
}
return &userpb.LinkAccountResponse{
Result: result,
User: &userpb.User{
Id: userID.Proto(),
View: &userpb.View{
PhoneNumber: req.GetPhone().PhoneNumber,
},
},
DataContainerId: dataContainerID.Proto(),
Metadata: &userpb.LinkAccountResponse_Phone{
Phone: metadata,
},
}, nil
}
func (s *identityServer) UnlinkAccount(ctx context.Context, req *userpb.UnlinkAccountRequest) (*userpb.UnlinkAccountResponse, error) {
log := s.log.WithField("method", "UnlinkAccount")
log = client.InjectLoggingMetadata(ctx, log)
ownerAccount, err := common.NewAccountFromProto(req.OwnerAccountId)
if err != nil {
log.WithError(err).Warn("owner account is invalid")
return nil, status.Error(codes.Internal, "")
}
log = log.WithField("owner_account", ownerAccount.PublicKey().ToBase58())
signature := req.Signature
req.Signature = nil
if err := s.auth.Authenticate(ctx, ownerAccount, req, signature); err != nil {
return nil, err
}
result := userpb.UnlinkAccountResponse_OK
switch identifer := req.IdentifyingFeature.(type) {
case *userpb.UnlinkAccountRequest_PhoneNumber:
log = log.WithField("phone", identifer.PhoneNumber.Value)
_, err := s.data.GetPhoneVerification(ctx, ownerAccount.PublicKey().ToBase58(), identifer.PhoneNumber.Value)
if err == phone.ErrVerificationNotFound {
result = userpb.UnlinkAccountResponse_NEVER_ASSOCIATED
break
} else if err != nil {
log.WithError(err).Warn("failure getting phone verification")
return nil, status.Error(codes.Internal, "")
}
trueVal := true
err = s.data.SaveOwnerAccountPhoneSetting(ctx, identifer.PhoneNumber.Value, &phone.OwnerAccountSetting{
OwnerAccount: ownerAccount.PublicKey().ToBase58(),
IsUnlinked: &trueVal,
CreatedAt: time.Now(),
LastUpdatedAt: time.Now(),
})
if err != nil {
log.WithError(err).Warn("failure disabling remote send setting")
return nil, status.Error(codes.Internal, "")
}
default:
return nil, status.Error(codes.InvalidArgument, "identifying_feature must be set")
}
return &userpb.UnlinkAccountResponse{
Result: result,
}, nil
}
func (s *identityServer) GetUser(ctx context.Context, req *userpb.GetUserRequest) (*userpb.GetUserResponse, error) {
log := s.log.WithField("method", "GetUser")
log = client.InjectLoggingMetadata(ctx, log)
ownerAccount, err := common.NewAccountFromProto(req.OwnerAccountId)
if err != nil {
log.WithError(err).Warn("owner account is invalid")
return nil, status.Error(codes.Internal, "")
}
log = log.WithField("owner_account", ownerAccount.PublicKey().ToBase58())
signature := req.Signature
req.Signature = nil
if err := s.auth.Authenticate(ctx, ownerAccount, req, signature); err != nil {
return nil, err
}
ownerManagementState, err := common.GetOwnerManagementState(ctx, s.data, ownerAccount)
if err != nil {
log.WithError(err).Warn("failure getting owner management state")
return nil, status.Error(codes.Internal, "")
}
var result userpb.GetUserResponse_Result
var userID *user.UserID
var isStaff bool
var dataContainerID *user.DataContainerID
var metadata *userpb.PhoneMetadata
switch identifer := req.IdentifyingFeature.(type) {
case *userpb.GetUserRequest_PhoneNumber:
log = log.WithField("phone", identifer.PhoneNumber.Value)
user, err := s.data.GetUserByPhoneView(ctx, identifer.PhoneNumber.Value)
if err == identity.ErrNotFound {
result = userpb.GetUserResponse_NOT_FOUND
break
} else if err != nil {
log.WithError(err).Warn("failure getting user identity from phone view")
return nil, status.Error(codes.Internal, "")
}
userID = user.ID
log = log.WithField("user", userID.String())
isStaff = user.IsStaffUser
// todo: needs a test
if user.IsBanned {
log.Info("banned user login denied")
result = userpb.GetUserResponse_NOT_FOUND
break
}
dataContainer, err := s.data.GetUserDataContainerByPhone(ctx, ownerAccount.PublicKey().ToBase58(), identifer.PhoneNumber.Value)
if err != nil {
log.WithError(err).Warn("failure getting data container for phone")
return nil, status.Error(codes.Internal, "")
}
dataContainerID = dataContainer.ID
if ownerManagementState == common.OwnerManagementStateUnlocked {
result = userpb.GetUserResponse_UNLOCKED_TIMELOCK_ACCOUNT
break
}
isLinked, err := s.data.IsPhoneNumberLinkedToAccount(ctx, identifer.PhoneNumber.Value, ownerAccount.PublicKey().ToBase58())
if err != nil {
log.WithError(err).Warn("failure getting link status to account")
return nil, status.Error(codes.Internal, "")
}
metadata = &userpb.PhoneMetadata{
IsLinked: isLinked,
}
default:
return nil, status.Error(codes.InvalidArgument, "identifying_feature must be set")
}
if result != userpb.GetUserResponse_OK {
return &userpb.GetUserResponse{
Result: result,
}, nil
}
// todo: Start centralizing airdrop intent logic somewhere
var eligibleAirdrops []transactionpb.AirdropType
userAgent, err := client.GetUserAgent(ctx)
if err == nil && userAgent.DeviceType == client.DeviceTypeIOS {
eligibleAirdrops = append(eligibleAirdrops, transactionpb.AirdropType_GET_FIRST_KIN)
}
for _, intentId := range []string{
transaction_server.GetNewAirdropIntentId(transaction_server.AirdropTypeGetFirstKin, ownerAccount.PublicKey().ToBase58()),
transaction_server.GetOldAirdropIntentId(transaction_server.AirdropTypeGetFirstKin, ownerAccount.PublicKey().ToBase58()),
} {
_, err = s.data.GetIntent(ctx, intentId)
if err == nil {
eligibleAirdrops = []transactionpb.AirdropType{}
break
} else if err != intent.ErrIntentNotFound {
log.WithError(err).Warnf("failure checking %s airdrop status", transactionpb.AirdropType_GET_FIRST_KIN)
return nil, status.Error(codes.Internal, "")
}
}
return &userpb.GetUserResponse{
Result: result,
User: &userpb.User{
Id: userID.Proto(),
View: &userpb.View{
PhoneNumber: req.GetPhoneNumber(),
},
},
DataContainerId: dataContainerID.Proto(),
Metadata: &userpb.GetUserResponse_Phone{
Phone: metadata,
},
EnableInternalFlags: isStaff,
EligibleAirdrops: eligibleAirdrops,
EnableBuyModule: s.conf.enableBuyModule.Get(ctx),
}, nil
}
func (s *identityServer) UpdatePreferences(ctx context.Context, req *userpb.UpdatePreferencesRequest) (*userpb.UpdatePreferencesResponse, error) {
log := s.log.WithField("method", "UpdatePreferences")
log = client.InjectLoggingMetadata(ctx, log)
ownerAccount, err := common.NewAccountFromProto(req.OwnerAccountId)
if err != nil {
log.WithError(err).Warn("owner account is invalid")
return nil, status.Error(codes.Internal, "")
}
log = log.WithField("owner_account", ownerAccount.PublicKey().ToBase58())
containerID, err := user.GetDataContainerIDFromProto(req.ContainerId)
if err != nil {
log.WithError(err).Warn("failure parsing data container id as uuid")
return nil, status.Error(codes.Internal, "")
}
log = log.WithField("data_container", containerID.String())
signature := req.Signature
req.Signature = nil
if err := s.auth.AuthorizeDataAccess(ctx, containerID, ownerAccount, req, signature); err != nil {
return nil, err
}
locale, err := language.Parse(req.Locale.Value)
if err != nil {
log.WithError(err).Info("client provided an invalid locale")
return &userpb.UpdatePreferencesResponse{
Result: userpb.UpdatePreferencesResponse_INVALID_LOCALE,
}, nil
}
record, err := s.data.GetUserPreferences(ctx, containerID)
if err == preferences.ErrPreferencesNotFound {
record = preferences.GetDefaultPreferences(containerID)
} else if err != nil {
log.WithError(err).Warn("failure getting preferences record")
return nil, status.Error(codes.Internal, "")
}
record.Locale = locale
err = s.data.SaveUserPreferences(ctx, record)
if err != nil {
log.WithError(err).Warn("failure saving preferences record")
return nil, status.Error(codes.Internal, "")
}
return &userpb.UpdatePreferencesResponse{
Result: userpb.UpdatePreferencesResponse_OK,
}, nil
}
func (s *identityServer) LoginToThirdPartyApp(ctx context.Context, req *userpb.LoginToThirdPartyAppRequest) (*userpb.LoginToThirdPartyAppResponse, error) {
log := s.log.WithField("method", "LoginToThirdPartyApp")
log = client.InjectLoggingMetadata(ctx, log)
intentId, err := common.NewAccountFromPublicKeyBytes(req.IntentId.Value)
if err != nil {
log.WithError(err).Warn("intent id is invalid")
return nil, err
}
log = log.WithField("intent", intentId.PublicKey().ToBase58())
userAuthorityAccount, err := common.NewAccountFromProto(req.UserId)
if err != nil {
log.WithError(err).Warn("invalid authority account")
return nil, status.Error(codes.Internal, "")
}
log = log.WithField("user", userAuthorityAccount.PublicKey().ToBase58())
signature := req.Signature
req.Signature = nil
if err := s.auth.Authenticate(ctx, userAuthorityAccount, req, signature); err != nil {
return nil, err
}
requestRecord, err := s.data.GetRequest(ctx, intentId.PublicKey().ToBase58())
if err == paymentrequest.ErrPaymentRequestNotFound {
return &userpb.LoginToThirdPartyAppResponse{
Result: userpb.LoginToThirdPartyAppResponse_REQUEST_NOT_FOUND,
}, nil
} else if err != nil {
log.WithError(err).Warn("failure getting request record")
return nil, status.Error(codes.Internal, "")
}
if !requestRecord.HasLogin() {
return &userpb.LoginToThirdPartyAppResponse{
Result: userpb.LoginToThirdPartyAppResponse_LOGIN_NOT_SUPPORTED,
}, nil
}
if requestRecord.RequiresPayment() {
return &userpb.LoginToThirdPartyAppResponse{
Result: userpb.LoginToThirdPartyAppResponse_PAYMENT_REQUIRED,
}, nil
}
var isValidLoginAccount bool
accountInfoRecord, err := s.data.GetAccountInfoByAuthorityAddress(ctx, userAuthorityAccount.PublicKey().ToBase58())
switch err {
case nil:
if accountInfoRecord.AccountType == commonpb.AccountType_RELATIONSHIP && *accountInfoRecord.RelationshipTo == *requestRecord.Domain {
isValidLoginAccount = true
}
case account.ErrAccountInfoNotFound:
default:
log.WithError(err).Warn("failure getting account info record")
return nil, status.Error(codes.Internal, "")
}
if !isValidLoginAccount {
return &userpb.LoginToThirdPartyAppResponse{
Result: userpb.LoginToThirdPartyAppResponse_INVALID_ACCOUNT,
}, nil
}
intentLock := s.intentLocks.Get(intentId.PublicKey().ToBytes())
intentLock.Lock()
defer intentLock.Unlock()
existingIntentRecord, err := s.data.GetIntent(ctx, intentId.PublicKey().ToBase58())
switch err {
case nil:
if accountInfoRecord.OwnerAccount == existingIntentRecord.InitiatorOwnerAccount {
return &userpb.LoginToThirdPartyAppResponse{
Result: userpb.LoginToThirdPartyAppResponse_OK,
}, nil
}
return &userpb.LoginToThirdPartyAppResponse{
Result: userpb.LoginToThirdPartyAppResponse_DIFFERENT_LOGIN_EXISTS,
}, nil
case intent.ErrIntentNotFound:
default:
log.WithError(err).Warn("failure checking for existing intent record")
return nil, status.Error(codes.Internal, "")
}
intentRecord := &intent.Record{
IntentId: intentId.PublicKey().ToBase58(),
IntentType: intent.Login,
LoginMetadata: &intent.LoginMetadata{
App: *requestRecord.Domain,
UserId: accountInfoRecord.AuthorityAccount,
},
InitiatorOwnerAccount: accountInfoRecord.OwnerAccount,
State: intent.StateConfirmed,
CreatedAt: time.Now(),
}
err = s.data.ExecuteInTx(ctx, sql.LevelDefault, func(ctx context.Context) error {
// todo: Ideally need a call with put semantics or proper distributed locks.
// Should be fine for now given the path uniquely handles the raw login
// case and everything happens in SubmitIntent.
err := s.data.SaveIntent(ctx, intentRecord)
if err != nil {
log.WithError(err).Warn("failure saving intent record")
return err
}
err = s.markWebhookAsPending(ctx, intentRecord.IntentId)
if err != nil {
log.WithError(err).Warn("failure marking webhook as pending")
return err
}
_, err = s.messagingClient.InternallyCreateMessage(ctx, intentId, &messagingpb.Message{
Kind: &messagingpb.Message_IntentSubmitted{
IntentSubmitted: &messagingpb.IntentSubmitted{
IntentId: &commonpb.IntentId{
Value: intentId.ToProto().Value,
},
// Metadata is hidden, since the details of who logged in should
// be gated behind an authenticated RPC
Metadata: nil,
},
},
})
if err != nil {
log.WithError(err).Warn("failure creating intent submitted message")
return err
}
return nil
})
if err != nil {
return nil, status.Error(codes.Internal, "")
}
return &userpb.LoginToThirdPartyAppResponse{
Result: userpb.LoginToThirdPartyAppResponse_OK,
}, nil
}
func (s *identityServer) GetLoginForThirdPartyApp(ctx context.Context, req *userpb.GetLoginForThirdPartyAppRequest) (*userpb.GetLoginForThirdPartyAppResponse, error) {
log := s.log.WithField("method", "GetLoginForThirdPartyApp")
log = client.InjectLoggingMetadata(ctx, log)
intentId, err := common.NewAccountFromPublicKeyBytes(req.IntentId.Value)
if err != nil {
log.WithError(err).Warn("intent id is invalid")
return nil, err
}
log = log.WithField("intent", intentId.PublicKey().ToBase58())
requestRecord, err := s.data.GetRequest(ctx, intentId.PublicKey().ToBase58())
if err == paymentrequest.ErrPaymentRequestNotFound {
return &userpb.GetLoginForThirdPartyAppResponse{
Result: userpb.GetLoginForThirdPartyAppResponse_REQUEST_NOT_FOUND,
}, nil
} else if err != nil {
log.WithError(err).Warn("failure getting request record")
return nil, status.Error(codes.Internal, "")
}
if !requestRecord.HasLogin() {
return &userpb.GetLoginForThirdPartyAppResponse{
Result: userpb.GetLoginForThirdPartyAppResponse_LOGIN_NOT_SUPPORTED,
}, nil
}
verifier, err := common.NewAccountFromProto(req.Verifier)
if err != nil {
log.WithError(err).Warn("invalid verifier")
return nil, status.Error(codes.Internal, "")
}
// todo: Promote a generic utility to the auth package?
isVerified, err := s.domainVerifier(ctx, verifier, *requestRecord.Domain)
if err != nil {
log.WithError(err).Warn("failure verifying domain ownership")
return nil, status.Errorf(codes.Unauthenticated, "error veryfing domain ownership: %s", err.Error())
} else if !isVerified {
return nil, status.Errorf(codes.Unauthenticated, "%s does not own the domain for the login", verifier.PublicKey().ToBase58())
}
intentRecord, err := s.data.GetIntent(ctx, intentId.PublicKey().ToBase58())
if err == intent.ErrIntentNotFound {
return &userpb.GetLoginForThirdPartyAppResponse{
Result: userpb.GetLoginForThirdPartyAppResponse_NO_USER_LOGGED_IN,
}, nil
} else if err != nil {
log.WithError(err).Warn("failure getting intent record")
return nil, status.Error(codes.Internal, "")
}
accountInfoRecord, err := s.data.GetRelationshipAccountInfoByOwnerAddress(ctx, intentRecord.InitiatorOwnerAccount, *requestRecord.Domain)
switch err {
case nil:
userId, err := common.NewAccountFromPublicKeyString(accountInfoRecord.AuthorityAccount)
if err != nil {
log.WithError(err).Warn("invalid authority account")
return nil, status.Error(codes.Internal, "")
}
return &userpb.GetLoginForThirdPartyAppResponse{
Result: userpb.GetLoginForThirdPartyAppResponse_OK,
UserId: userId.ToProto(),
}, nil
case account.ErrAccountInfoNotFound:
// The client opted to not establish a relationship, so there's no login
return &userpb.GetLoginForThirdPartyAppResponse{
Result: userpb.GetLoginForThirdPartyAppResponse_NO_USER_LOGGED_IN,
}, nil
default:
log.WithError(err).Warn("failure getting relationship account info record")
return nil, status.Error(codes.Internal, "")
}
}
func (s *identityServer) GetTwitterUser(ctx context.Context, req *userpb.GetTwitterUserRequest) (*userpb.GetTwitterUserResponse, error) {
log := s.log.WithField("method", "GetTwitterUser")
log = client.InjectLoggingMetadata(ctx, log)
var record *twitter.Record
var err error
switch typed := req.Query.(type) {
case *userpb.GetTwitterUserRequest_Username:
log = log.WithField("username", typed.Username)
record, err = s.data.GetTwitterUserByUsername(ctx, typed.Username)
case *userpb.GetTwitterUserRequest_TipAddress:
log = log.WithField("tip_address", base58.Encode(typed.TipAddress.Value))
record, err = s.data.GetTwitterUserByTipAddress(ctx, base58.Encode(typed.TipAddress.Value))
default:
return nil, status.Error(codes.InvalidArgument, "req.query must be set")
}
switch err {
case nil:
tipAddress, err := common.NewAccountFromPublicKeyString(record.TipAddress)
if err != nil {
log.WithError(err).Warn("tip address is invalid")
return nil, status.Error(codes.Internal, "")
}
return &userpb.GetTwitterUserResponse{
Result: userpb.GetTwitterUserResponse_OK,
TwitterUser: &userpb.TwitterUser{
TipAddress: tipAddress.ToProto(),
Username: record.Username,
Name: record.Name,
ProfilePicUrl: record.ProfilePicUrl,
VerifiedType: record.VerifiedType,
FollowerCount: record.FollowerCount,
},
}, nil
case twitter.ErrUserNotFound:
return &userpb.GetTwitterUserResponse{
Result: userpb.GetTwitterUserResponse_NOT_FOUND,
}, nil
default:
log.WithError(err).Warn("failure getting twitter user info")
return nil, status.Error(codes.Internal, "")
}
}
func (s *identityServer) markWebhookAsPending(ctx context.Context, id string) error {
webhookRecord, err := s.data.GetWebhook(ctx, id)
if err == webhook.ErrNotFound {
return nil
} else if err != nil {
return err
}
if webhookRecord.State != webhook.StateUnknown {
return nil
}
webhookRecord.NextAttemptAt = pointer.Time(time.Now())
webhookRecord.State = webhook.StatePending
return s.data.UpdateWebhook(ctx, webhookRecord)
}