-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathSequenceLogin.cs
More file actions
726 lines (629 loc) · 28.7 KB
/
SequenceLogin.cs
File metadata and controls
726 lines (629 loc) · 28.7 KB
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
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Sequence.Authentication;
using Sequence.Config;
using Sequence.Utils;
using Sequence.Utils.SecureStorage;
using Sequence.Wallet;
using UnityEngine;
namespace Sequence.EmbeddedWallet
{
public class SequenceLogin : ILogin, IWaaSConnector
{
public static string WaaSWithAuthUrl { get; private set; }
public const string WaaSLoginMethod = "WaaSLoginMethod";
public const string EmailInUseError = "EmailAlreadyInUse";
private int _waasProjectId;
private string _waasVersion;
private IAuthenticator _authenticator;
private IValidator _validator;
private EOAWallet _sessionWallet;
private string _sessionId;
private IntentSender _intentSender;
private EmailConnector _emailConnector;
private IWaaSConnector _connector;
private bool _isLoggingIn = false;
private bool _storeSessionWallet = false;
private const string _walletKey = "SessionWallet";
private IntentDataOpenSession _failedLoginIntent;
private LoginMethod _failedLoginMethod;
private string _failedLoginEmail;
private bool _automaticallyFederateAccountsWhenPossible;
private Address _connectedWalletAddress;
private static SequenceLogin _instance;
private string _verifierToReject; // Since email auth is two separate requests, an invalid signature error may go unnoticed. So, we cache the verifier used in an initiateAuth attempt that had an invalid signature and reject the corresponding openSession attempt if it uses the same verifier.
public static SequenceLogin GetInstance(IValidator validator = null, IAuthenticator authenticator = null,
IWaaSConnector connector = null, bool automaticallyFederateAccountsWhenPossible = true,
Address connectedWalletAddress = null)
{
if (_instance == null)
{
_instance = new SequenceLogin(validator, authenticator, connector, automaticallyFederateAccountsWhenPossible, connectedWalletAddress);
}
if (connectedWalletAddress != null)
{
_instance.SetConnectedWalletAddress(connectedWalletAddress);
}
_instance.SetupAuthenticator();
return _instance;
}
public static SequenceLogin GetInstanceToFederateAuth(Address connectedWalletAddress, IValidator validator = null,
IAuthenticator authenticator = null,
IWaaSConnector connector = null, bool automaticallyFederateAccountsWhenPossible = true)
{
if (_instance == null)
{
_instance = new SequenceLogin(validator, authenticator, connector, automaticallyFederateAccountsWhenPossible, connectedWalletAddress);
}
_instance.SetConnectedWalletAddress(connectedWalletAddress);
return _instance;
}
public void SetConnectedWalletAddress(Address connectedWalletAddress)
{
if (connectedWalletAddress == null)
{
SequenceLog.Error($"The connected wallet address cannot be null or empty.");
throw new ArgumentNullException(nameof(connectedWalletAddress));
}
_connectedWalletAddress = connectedWalletAddress;
}
public void RemoveConnectedWalletAddress()
{
_connectedWalletAddress = null;
}
[Obsolete("Use GetInstance() instead.")]
public SequenceLogin(IValidator validator = null, IAuthenticator authenticator = null, IWaaSConnector connector = null, bool automaticallyFederateAccountsWhenPossible = true, Address connectedWalletAddress = null)
{
if (connector == null)
{
connector = this;
}
_connector = connector;
_automaticallyFederateAccountsWhenPossible = automaticallyFederateAccountsWhenPossible;
if (connectedWalletAddress != null)
{
SetConnectedWalletAddress(connectedWalletAddress);
}
bool storeSessionWallet = SequenceConfig.GetConfig(SequenceService.WaaS).StoreSessionKey() && SecureStorageFactory.IsSupportedPlatform() && connectedWalletAddress == null;
if (storeSessionWallet)
{
_storeSessionWallet = true;
Configure();
}
else
{
CreateWallet(validator, authenticator);
}
}
private void CreateWallet(IValidator validator = null, IAuthenticator authenticator = null)
{
Configure();
SetupAuthenticator(validator, authenticator);
}
public void ResetSessionId()
{
if (_connectedWalletAddress != null) {
return;
}
_sessionWallet = new EOAWallet();
_sessionId = IntentDataOpenSession.CreateSessionId(_sessionWallet.GetAddress());
_intentSender = new IntentSender(new HttpClient(WaaSWithAuthUrl), _sessionWallet, _sessionId, _waasProjectId, _waasVersion);
_emailConnector = new EmailConnector(_sessionId, _sessionWallet, _connector, _validator);
}
/// <summary>
/// Use this to reset the authenticator, validator, and other dependancies to new instances. Useful for when you're testing and using mock implementations
/// </summary>
public void ResetLoginAfterTest()
{
_connector = this;
RemoveConnectedWalletAddress();
SetupAuthenticator();
}
public void SetupAuthenticator(IValidator validator = null, IAuthenticator authenticator = null)
{
ConfigJwt configJwt = SequenceConfig.GetConfigJwt(SequenceConfig.GetConfig(SequenceService.WaaS));
if (_sessionWallet == null)
{
_sessionWallet = new EOAWallet();
}
_sessionId = IntentDataOpenSession.CreateSessionId(_sessionWallet.GetAddress());
_intentSender = new IntentSender(new HttpClient(WaaSWithAuthUrl, true), _sessionWallet, _sessionId, _waasProjectId, _waasVersion);
if (authenticator != null)
{
_authenticator = authenticator;
}
else
{
_authenticator = new OpenIdAuthenticator();
}
SetupAuthenticatorAndListeners();
if (validator == null)
{
validator = new Validator();
}
_validator = validator;
_emailConnector = new EmailConnector(_sessionId, _sessionWallet, _connector, _validator);
}
/// <summary>
/// Recover the current session asynchronously and get the associated wallet.
/// </summary>
/// <returns>
/// Returns StorageEnabled bool indicating if the SDK is configured to store sessions.
/// Returns Instance of IWallet if the session was recovered. Returns null if no session was found.
/// </returns>
public async Task<(bool StorageEnabled, IWallet Wallet)> TryToRestoreSessionAsync()
{
var config = SequenceConfig.GetConfig();
var storeSessionInfoAndSkipLoginWhenPossible = config.StoreSessionKey();
if (!SecureStorageFactory.IsSupportedPlatform() || !storeSessionInfoAndSkipLoginWhenPossible)
return (false, null);
var done = false;
SequenceWallet wallet = null;
SequenceWallet.OnFailedToRecoverSession += HandleFailedToRecover;
SequenceWallet.OnWalletCreated += HandleRecoveredWallet;
TryToRestoreSession();
SetupAuthenticator();
while (!done)
await Task.Yield();
return (true, wallet);
void HandleRecoveredWallet(SequenceWallet newWallet)
{
wallet = newWallet;
done = true;
SequenceWallet.OnFailedToRecoverSession -= HandleFailedToRecover;
SequenceWallet.OnWalletCreated -= HandleRecoveredWallet;
}
void HandleFailedToRecover(string error)
{
HandleRecoveredWallet(null);
}
}
public void TryToRestoreSession()
{
if (!_storeSessionWallet)
{
return;
}
if (_connectedWalletAddress != null)
{
FailedLoginWithStoredSessionWallet("Cannot restore session when connected wallet address is set");
return;
}
TryToLoginWithStoredSessionWallet();
}
public async Task GuestLogin()
{
await ConnectToWaaSAsGuest();
}
private void SetupAuthenticatorAndListeners()
{
try {
_authenticator.PlatformSpecificSetup();
}
catch (Exception e) {
SequenceLog.Error($"Error encountered during PlatformSpecificSetup: {e.Message}\nSocial sign in will not work.");
}
Application.deepLinkActivated += _authenticator.HandleDeepLink;
_authenticator.SignedIn += OnSocialLogin;
_authenticator.OnSignInFailed += OnSocialSignInFailed;
}
private void Configure()
{
SequenceConfig config = SequenceConfig.GetConfig(SequenceService.WaaS);
string waasVersion = config.WaaSVersion;
if (string.IsNullOrWhiteSpace(waasVersion))
{
throw SequenceConfig.MissingConfigError("WaaS Version");
}
_waasVersion = waasVersion;
ConfigJwt configJwt = SequenceConfig.GetConfigJwt(config);
string rpcUrl = configJwt.rpcServer;
if (string.IsNullOrWhiteSpace(rpcUrl))
{
throw SequenceConfig.MissingConfigError("RPC Server");
}
WaaSWithAuthUrl = $"{rpcUrl.AppendTrailingSlashIfNeeded()}rpc/WaasAuthenticator";
int projectId = configJwt.projectId;
if (string.IsNullOrWhiteSpace(projectId.ToString()))
{
throw SequenceConfig.MissingConfigError("Project ID");
}
_waasProjectId = projectId;
}
private void TryToLoginWithStoredSessionWallet()
{
(EOAWallet, string, string) walletInfo = (null, "", "");
try
{
walletInfo = AttemptToCreateWalletFromSecureStorage();
}
catch (Exception e)
{
FailedLoginWithStoredSessionWallet(e.Message);
return;
}
if (walletInfo.Item1 == null || string.IsNullOrWhiteSpace(walletInfo.Item2))
{
FailedLoginWithStoredSessionWallet("No stored wallet info found");
return;
}
_sessionWallet = walletInfo.Item1;
_sessionId = IntentDataOpenSession.CreateSessionId(_sessionWallet.GetAddress());
SequenceWallet wallet = new SequenceWallet(new Address(walletInfo.Item2), _sessionId, new IntentSender(new HttpClient(WaaSWithAuthUrl), walletInfo.Item1, _sessionId, _waasProjectId, _waasVersion), walletInfo.Item3);
EnsureSessionIsValid(wallet);
}
private void FailedLoginWithStoredSessionWallet(string error)
{
CreateWallet();
SequenceWallet.OnFailedToRecoverSession?.Invoke(error);
}
private async Task EnsureSessionIsValid(SequenceWallet wallet)
{
Session[] activeSessions = await wallet.ListSessions();
if (activeSessions == null || activeSessions.Length == 0)
{
FailedLoginWithStoredSessionWallet("No active sessions found");
return;
}
int sessions = activeSessions.Length;
string expectedSessionId = wallet.SessionId;
for (int i = 0; i < sessions; i++)
{
if (activeSessions[i].id == expectedSessionId)
{
SequenceWallet.OnWalletCreated?.Invoke(wallet);
return;
}
}
FailedLoginWithStoredSessionWallet("Stored session wallet is not active");
}
private (EOAWallet, string, string) AttemptToCreateWalletFromSecureStorage()
{
ISecureStorage secureStorage = SecureStorageFactory.CreateSecureStorage();
string walletInfo = secureStorage.RetrieveString(Application.companyName + "-" + Application.productName + "-" + _walletKey);
if (string.IsNullOrEmpty(walletInfo))
{
return (null, "", "");
}
string[] walletInfoSplit = walletInfo.Split('-');
string privateKey = walletInfoSplit[0];
string walletAddress = walletInfoSplit[1];
string email = "";
if (walletInfoSplit.Length == 3)
{
email = walletInfoSplit[2];
}
EOAWallet wallet = new EOAWallet(privateKey);
return (wallet, walletAddress, email);
}
public event ILogin.OnLoginSuccessHandler OnLoginSuccess;
public event ILogin.OnLoginFailedHandler OnLoginFailed;
public event ILogin.OnMFAEmailSentHandler OnMFAEmailSent;
public event ILogin.OnMFAEmailFailedToSendHandler OnMFAEmailFailedToSend;
public async Task Login(string email)
{
ResetSessionId();
try
{
_isLoggingIn = true;
await _emailConnector.Login(email);
OnMFAEmailSent?.Invoke(email);
}
catch (Exception e)
{
OnMFAEmailFailedToSend?.Invoke(email, e.Message);
}
}
public async Task Login(string email, string code)
{
_isLoggingIn = true;
if (_connectedWalletAddress != null)
{
await FederateEmail(email, code, _connectedWalletAddress);
}
else
{
await _emailConnector.ConnectToWaaSViaEmail(email, code);
}
}
public void GoogleLogin()
{
_authenticator.GoogleSignIn();
}
public void DiscordLogin()
{
_authenticator.DiscordSignIn();
}
public void FacebookLogin()
{
_authenticator.FacebookSignIn();
}
public void AppleLogin()
{
_authenticator.AppleSignIn();
}
public bool IsLoggingIn()
{
return _isLoggingIn;
}
private void OnSocialLogin(OpenIdAuthenticationResult result)
{
ResetSessionId();
if (_connectedWalletAddress != null)
{
FederateAccountSocial(result.IdToken, result.Method, _connectedWalletAddress);
}
else
{
ConnectToWaaSViaSocialLogin(result.IdToken, result.Method);
}
}
private void OnSocialSignInFailed(string error, LoginMethod method)
{
OnLoginFailed?.Invoke($"Connecting to WaaS API failed due to error with {method} sign in: {error}", method);
}
public async Task ConnectToWaaS(IntentDataOpenSession loginIntent, LoginMethod method, string email = "")
{
string walletAddress = "";
if (_verifierToReject == loginIntent.verifier)
{
OnLoginFailed?.Invoke("The initiateAuth request associated with this login attempt received a response with an invalid signature. For security reasons, this login request will not be sent to the API as your network traffic may be being monitored. Please try initiating auth again.", method);
_isLoggingIn = false;
return;
}
try
{
IntentResponseSessionOpened registerSessionResponse = await _intentSender.SendIntent<IntentResponseSessionOpened, IntentDataOpenSession>(loginIntent, IntentType.OpenSession);
string sessionId = registerSessionResponse.sessionId;
walletAddress = registerSessionResponse.wallet;
OnLoginSuccess?.Invoke(sessionId, walletAddress);
SequenceWallet wallet = new SequenceWallet(new Address(walletAddress), sessionId, new IntentSender(new HttpClient(SequenceLogin.WaaSWithAuthUrl), _sessionWallet, sessionId, _waasProjectId, _waasVersion), email);
PlayerPrefs.SetInt(WaaSLoginMethod, (int)method);
PlayerPrefs.SetString(OpenIdAuthenticator.LoginEmail, email);
PlayerPrefs.Save();
_isLoggingIn = false;
wallet.OnDropSessionComplete += session =>
{
if (session == sessionId)
{
_connectedWalletAddress = null;
}
};
SequenceWallet.OnWalletCreated?.Invoke(wallet);
}
catch (Exception e)
{
var emailInUse = e.Message.Contains(EmailInUseError);
if (emailInUse)
{
List<LoginMethod> associatedLoginMethods = ParseLoginMethods(e.Message);
OnLoginFailed?.Invoke("Error registering session: " + e.Message, method, email, associatedLoginMethods);
_failedLoginIntent = loginIntent;
_failedLoginMethod = method;
_failedLoginEmail = email;
}
else
{
OnLoginFailed?.Invoke("Error registering session: " + e.Message, method, email);
}
_isLoggingIn = false;
return;
}
if (_automaticallyFederateAccountsWhenPossible && _failedLoginEmail == email && !loginIntent.forceCreateAccount) // forceCreateAccount should only be true if we are creating another account for the same email address, meaning we don't have a failed login method that needs federating
{
await FederateAccount(new IntentDataFederateAccount(_failedLoginIntent, walletAddress), _failedLoginMethod, email);
}
try
{
if (_storeSessionWallet && SecureStorageFactory.IsSupportedPlatform())
{
StoreWalletSecurely(walletAddress, email);
}
}
catch (Exception e)
{
SequenceLog.Error("Error storing session wallet securely: " + e.Message);
}
}
private List<LoginMethod> ParseLoginMethods(string errorMessage)
{
if (!errorMessage.Contains(EmailInUseError))
{
throw new ArgumentException($"Error message must contain {EmailInUseError}. Given: {errorMessage}");
}
string[] errorComponents = errorMessage.Split('{');
string errorLeft = "{" + errorComponents[1];
errorComponents = errorLeft.Split('}');
string error = errorComponents[0] + "}";
ErrorResponse response = JsonConvert.DeserializeObject<ErrorResponse>(error);
string cause = response.cause;
string[] methodStrings = cause.Split(',');
List<LoginMethod> methods = new List<LoginMethod>();
int count = methodStrings.Length;
for (int i = 0; i < count; i++)
{
string[] components = methodStrings[i].Trim().Split('|');
IdentityType identityType = (IdentityType)Enum.Parse(typeof(IdentityType), components[0]);
switch (identityType)
{
case IdentityType.OIDC:
if (components.Length < 3)
{
SequenceLog.Error(
"Invalid response from WaaS server, expected at least 3 components in OIDC login method string");
}
if (components[2].Contains("google"))
{
methods.Add(LoginMethod.Google);
}
else if (components[2].Contains("apple"))
{
methods.Add(LoginMethod.Apple);
}
else if (components[2].Contains("discord"))
{
methods.Add(LoginMethod.Discord);
}
else if (components[2].Contains("facebook"))
{
methods.Add(LoginMethod.Facebook);
}
else
{
SequenceLog.Error("Unexpected OIDC login method string: " + components[2]);
}
break;
case IdentityType.Email:
methods.Add(LoginMethod.Email);
break;
case IdentityType.Guest:
methods.Add(LoginMethod.Guest);
break;
case IdentityType.PlayFab:
methods.Add(LoginMethod.PlayFab);
break;
default:
SequenceLog.Error("Unexpected identity type " + identityType);
break;
}
}
return methods;
}
public async Task<string> InitiateAuth(IntentDataInitiateAuth initiateAuthIntent, LoginMethod method)
{
string challenge = "";
try
{
IntentResponseAuthInitiated initiateAuthResponse = await _intentSender.SendIntent<IntentResponseAuthInitiated, IntentDataInitiateAuth>(initiateAuthIntent, IntentType.InitiateAuth);
string sessionId = initiateAuthResponse.sessionId;
if (sessionId != _sessionId)
{
throw new Exception($"Session Id received from WaaS server doesn't match, received {sessionId}, sent {_sessionId}");
}
if (!initiateAuthResponse.ValidateChallenge()) {
throw new Exception("Invalid challenge received from WaaS server, received: " + initiateAuthResponse.challenge);
}
challenge = initiateAuthResponse.challenge;
}
catch (Exception e)
{
string error = "Error initiating auth: " + e.Message;
if (error.Contains("Error validating response"))
{
_verifierToReject = initiateAuthIntent.verifier;
}
OnLoginFailed?.Invoke(error, method);
_isLoggingIn = false;
throw new Exception(error);
}
return challenge;
}
public async Task ConnectToWaaSViaSocialLogin(string idToken, LoginMethod method)
{
if (!method.IsOIDC())
{
OnLoginFailed?.Invoke($"Invalid login method, given: {method}, expected one of {nameof(IdentityType)}: {nameof(IdentityType.OIDC)}", method);
_isLoggingIn = false;
return;
}
_isLoggingIn = true;
OIDCConnector oidcConnector = new OIDCConnector(idToken, _sessionId, _sessionWallet, _connector);
await oidcConnector.ConnectToWaaSViaSocialLogin(method);
}
public void PlayFabLogin(string titleId, string sessionTicket, string email)
{
ResetSessionId();
if (_connectedWalletAddress != null)
{
FederateAccountPlayFab(titleId, sessionTicket, email, _connectedWalletAddress);
}
else
{
ConnectToWaaSViaPlayFab(titleId, sessionTicket, email);
}
}
public void ForceCreateAccount()
{
ForceCreateWaaSAccount();
}
private async Task ForceCreateWaaSAccount()
{
if (string.IsNullOrEmpty(_failedLoginEmail))
throw new Exception("Failed to force create account.");
_failedLoginIntent.forceCreateAccount = true;
await ConnectToWaaS(_failedLoginIntent, _failedLoginMethod, _failedLoginEmail);
PlayerPrefs.SetInt(WaaSLoginMethod, (int)_failedLoginMethod);
PlayerPrefs.SetString(OpenIdAuthenticator.LoginEmail, _failedLoginEmail);
PlayerPrefs.Save();
}
public async Task ConnectToWaaSViaPlayFab(string titleId, string sessionTicket, string email)
{
if (string.IsNullOrWhiteSpace(titleId) || string.IsNullOrWhiteSpace(sessionTicket))
{
OnLoginFailed?.Invoke($"Invalid titleId: {titleId} or sessionTicket: {sessionTicket}", LoginMethod.PlayFab);
_isLoggingIn = false;
return;
}
_isLoggingIn = true;
PlayFabConnector playFabConnector = new PlayFabConnector(titleId, sessionTicket, _sessionId, _sessionWallet, _connector);
await playFabConnector.ConnectToWaaSViaPlayFab(email);
}
public async Task ConnectToWaaSAsGuest()
{
ResetSessionId();
_isLoggingIn = true;
GuestConnector connector = new GuestConnector(_sessionId, _sessionWallet, _connector);
await connector.ConnectToWaaSViaGuest();
}
internal void StoreWalletSecurely(string waasWalletAddress, string email)
{
if (!_storeSessionWallet || !SecureStorageFactory.IsSupportedPlatform()) return;
ISecureStorage secureStorage = SecureStorageFactory.CreateSecureStorage();
byte[] privateKeyBytes = new byte[32];
_sessionWallet.privKey.WriteToSpan(privateKeyBytes);
string privateKey = privateKeyBytes.ByteArrayToHexString();
secureStorage.StoreString(Application.companyName + "-" + Application.productName + "-" + _walletKey, privateKey + "-" + waasWalletAddress + "-" + email);
}
public async Task FederateAccount(IntentDataFederateAccount federateAccount, LoginMethod method, string email)
{
try
{
IntentResponseAccountFederated federateAccountResponse = await _intentSender.SendIntent<IntentResponseAccountFederated, IntentDataFederateAccount>(federateAccount, IntentType.FederateAccount);
Account account = federateAccountResponse.account;
account.wallet = new Address(federateAccount.wallet);
string responseEmail = account.email;
if (responseEmail != email.ToLower())
{
throw new Exception($"Email received from WaaS server doesn't match, received {responseEmail}, sent {email}");
}
PlayerPrefs.SetInt(WaaSLoginMethod, (int)method);
PlayerPrefs.SetString(OpenIdAuthenticator.LoginEmail, email);
PlayerPrefs.Save();
_failedLoginEmail = "";
_failedLoginIntent = null;
_failedLoginMethod = LoginMethod.None;
SequenceWallet.OnAccountFederated?.Invoke(account);
}
catch (Exception e)
{
SequenceWallet.OnAccountFederationFailed?.Invoke("Error federating account: " + e.Message);
}
}
public async Task FederateAccountPlayFab(string titleId, string sessionTicket, string email, string walletAddress)
{
PlayFabConnector playFabConnector = new PlayFabConnector(titleId, sessionTicket, _sessionId, _sessionWallet, _connector);
await playFabConnector.FederateAccount(email, walletAddress);
}
public async Task FederateAccountSocial(string idToken, LoginMethod method, string walletAddress)
{
OIDCConnector oidcConnector = new OIDCConnector(idToken, _sessionId, _sessionWallet, _connector);
await oidcConnector.FederateAccount(method, walletAddress);
}
public async Task FederateEmail(string email, string code, string walletAddress)
{
await _emailConnector.FederateAccount(email, code, walletAddress);
}
}
}