-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathAvatarManager.cs
More file actions
1773 lines (1506 loc) · 88.1 KB
/
AvatarManager.cs
File metadata and controls
1773 lines (1506 loc) · 88.1 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
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using NextGenSoftware.Utilities;
using NextGenSoftware.OASIS.Common;
using NextGenSoftware.OASIS.API.DNA;
using NextGenSoftware.OASIS.API.Core.Enums;
using NextGenSoftware.OASIS.API.Core.Interfaces;
using NextGenSoftware.OASIS.API.Core.Objects;
using NextGenSoftware.OASIS.API.Core.Holons;
using NextGenSoftware.OASIS.API.Core.Helpers;
using NextGenSoftware.OASIS.API.Core.Objects.Search.Avatrar;
using NextGenSoftware.OASIS.API.Core.Objects.Search;
using NextGenSoftware.OASIS.API.Core.Interfaces.Search;
using NextGenSoftware.OASIS.API.Core.Objects.Avatar;
namespace NextGenSoftware.OASIS.API.Core.Managers
{
public partial class AvatarManager : OASISManager
{
private static AvatarManager _instance = null;
private ProviderManagerConfig _config;
private static IAvatar _loggedInAvatar = null;
//public static IAvatar OASISSystemAccount { get; set; } //TODO: Later may need to actually create a avatar for this Id? So we can see which ids belong to OASIS Accounts outside of each ONODE (each ONODE has its own OASISDNA with its own system id's).
public static IAvatar LoggedInAvatar
{
get
{
//If there is no logged in user then default to the OASIS System Account Id. //TODO: May need to look into this in more detail later to work out all use/edge cases etc...
if (_loggedInAvatar == null && !string.IsNullOrEmpty(Instance.OASISDNA.OASIS.OASISSystemAccountId))
_loggedInAvatar = new Avatar() { Id = new Guid(Instance.OASISDNA.OASIS.OASISSystemAccountId) };
return _loggedInAvatar;
}
set
{
_loggedInAvatar = value;
}
}
public static Dictionary<string, IAvatar> LoggedInAvatarSessions { get; set; }
//public List<IOASISStorageProvider> OASISStorageProviders { get; set; }
//TODO Implement this singleton pattern for other Managers...
public static AvatarManager Instance
{
get
{
if (_instance == null)
_instance = new AvatarManager(ProviderManager.Instance.CurrentStorageProvider, ProviderManager.Instance.OASISDNA);
return _instance;
}
}
public ProviderManagerConfig Config
{
get
{
if (_config == null)
_config = new ProviderManagerConfig();
return _config;
}
}
//public delegate void StorageProviderError(object sender, AvatarManagerErrorEventArgs e);
//TODO: Not sure we want to pass the OASISDNA here?
public AvatarManager(IOASISStorageProvider OASISStorageProvider, OASISDNA OASISDNA = null) : base(OASISStorageProvider, OASISDNA)
{
}
// TODO: Not sure if we want to move methods from the AvatarService in WebAPI here?
// For integration with STAR and others like Unity can just call the REST API service?
// What advantage is there to making it native through dll's? Would be slightly faster than having to make a HTTP request/response round trip...
// BUT would STILL need to call out to a OASIS Storage Provider so depending if that was also running locally is how fast it would be...
// For now just easier to call the REST API service from STAR... can come back to this later... :)
public OASISResult<IAvatar> Authenticate(string username, string password, string ipAddress)
{
//They can log in with either username, email or a public key linked to the avatar.
OASISResult<IAvatar> result = null;
try
{
//Temp supress logging to the console in case STAR CLI is creating a new avatar...
//CLIEngine.SupressConsoleLogging = true;
//Temp disable the OASIS HyperDrive so it returns fast and does not attempt to find the avatar across all providers! ;-)
//TODO: May want to fine tune how we handle this in future?
//bool isAutoFailOverEnabled = ProviderManager.Instance.IsAutoFailOverEnabled;
//ProviderManager.Instance.IsAutoFailOverEnabled = false;
List<EnumValue<ProviderType>> currentProviderFailOverList = ProviderManager.Instance.GetProviderAutoFailOverList();
ProviderManager.Instance.SetAndReplaceAutoFailOverListForProviders(ProviderManager.Instance.GetProviderAutoFailOverListForAvatarLogin());
//First try by username...
result = LoadAvatar(username, false, false);
if (result.Result == null)
{
//Now try by email...
result = LoadAvatarByEmail(username, false, false);
if (result.Result == null)
{
//Finally by Public Key...
//TODO: Make this more efficient so we do not need to load all avatars!
OASISResult<IEnumerable<IAvatar>> avatarsResult = LoadAllAvatars();
if (!avatarsResult.IsError && avatarsResult.Result != null)
{
if (avatarsResult.Result.Any(x => x.ProviderWallets.ContainsKey(ProviderManager.Instance.CurrentStorageProviderType.Value)))
result.Result = avatarsResult.Result.FirstOrDefault(x => x.ProviderWallets[ProviderManager.Instance.CurrentStorageProviderType.Value].Any(x => x.PublicKey == username));
}
}
}
if (result.Result == null)
result.Message = $"This avatar does not exist. Please contact support or create a new avatar.";
else
{
result = ProcessAvatarLogin(result, password);
//TODO: Come back to this.
//if (OASISDNA.OASIS.Security.AvatarPassword.)
if (result.Result != null & !result.IsError)
{
var jwtToken = GenerateJWTToken(result.Result);
var refreshToken = generateRefreshToken(ipAddress);
if (result.Result.RefreshTokens == null)
result.Result.RefreshTokens = new List<RefreshToken>();
result.Result.RefreshTokens.Add(refreshToken);
result.Result.JwtToken = jwtToken;
result.Result.RefreshToken = refreshToken.Token;
result.Result.LastBeamedIn = DateTime.Now;
result.Result.IsBeamedIn = true;
LoggedInAvatar = result.Result;
OASISResult<IAvatar> saveAvatarResult = SaveAvatar(result.Result);
if (!saveAvatarResult.IsError && saveAvatarResult.IsSaved)
{
result.Result = HideAuthDetails(saveAvatarResult.Result, false, true, false, false);
result.IsSaved = true;
result.Message = "Avatar Successfully Authenticated.";
}
else
OASISErrorHandling.HandleError(ref result, $"Error occured in Authenticate method in AvatarManager whilst saving the avatar. Reason: {saveAvatarResult.Message}", saveAvatarResult.DetailedMessage);
}
else
result.Result = null;
}
ProviderManager.Instance.SetAndReplaceAutoFailOverListForProviders(currentProviderFailOverList);
//ProviderManager.Instance.IsAutoFailOverEnabled = isAutoFailOverEnabled;
//CLIEngine.SupressConsoleLogging = false;
}
catch (Exception ex)
{
OASISErrorHandling.HandleError(ref result, string.Concat("Unknown error occured in Authenticate method in AvatarManager. Error Message: ", ex.Message), ex);
result.Result = null;
}
return result;
}
public delegate OASISResult<IAvatar> SaveAvatarFunction(IAvatar avatar);
public async Task<OASISResult<IAvatar>> AuthenticateAsync(string username, string password, string ipAddress, AutoReplicationMode autoReplicationMode = AutoReplicationMode.UseGlobalDefaultInOASISDNA, AutoFailOverMode autoFailOverMode = AutoFailOverMode.UseGlobalDefaultInOASISDNA, AutoLoadBalanceMode autoLoadBalanceMode = AutoLoadBalanceMode.UseGlobalDefaultInOASISDNA, bool waitForAutoReplicationResult = false)
{
//They can log in with either username, email or a public key linked to the avatar.
OASISResult<IAvatar> result = null;
try
{
//Temp supress logging to the console in case STAR CLI is creating a new avatar...
//CLIEngine.SupressConsoleLogging = true;
//Temp disable the OASIS HyperDrive so it returns fast and does not attempt to find the avatar across all providers! ;-)
//TODO: May want to fine tune how we handle this in future?
//bool isAutoFailOverEnabled = ProviderManager.Instance.IsAutoFailOverEnabled;
//ProviderManager.Instance.IsAutoFailOverEnabled = false;
List<EnumValue<ProviderType>> currentProviderFailOverList = ProviderManager.Instance.GetProviderAutoFailOverList();
ProviderManager.Instance.SetAndReplaceAutoFailOverListForProviders(ProviderManager.Instance.GetProviderAutoFailOverListForAvatarLogin());
//First try by username...
result = await LoadAvatarAsync(username, false, false);
if (result.Result == null)
{
//Now try by email...
result = await LoadAvatarByEmailAsync(username, false, false);
if (result.Result == null)
{
//Finally by Public Key...
OASISResult<IEnumerable<IAvatar>> avatarsResult = await LoadAllAvatarsAsync(false);
if (!avatarsResult.IsError && avatarsResult.Result != null)
{
if (avatarsResult.Result.Any(x => x.ProviderWallets.ContainsKey(ProviderManager.Instance.CurrentStorageProviderType.Value)))
result.Result = avatarsResult.Result.FirstOrDefault(x => x.ProviderWallets[ProviderManager.Instance.CurrentStorageProviderType.Value].Any(x => x.PublicKey == username));
}
}
}
if (result.Result == null)
result.Message = $"This avatar does not exist. Please contact support or create a new avatar.";
else
{
//ProcessAvatarLogin(result, username, password, ipAddress, (result.Result) => { SaveAvatar(result.Result); }) ;
// ProcessAvatarLogin(result, username, password, ipAddress, SaveAvatar);
result = ProcessAvatarLogin(result, password);
//TODO: Come back to this.
//if (OASISDNA.OASIS.Security.AvatarPassword.)
if (result.Result != null & !result.IsError)
{
var jwtToken = GenerateJWTToken(result.Result);
var refreshToken = generateRefreshToken(ipAddress);
if (result.Result.RefreshTokens == null)
result.Result.RefreshTokens = new List<RefreshToken>();
result.Result.RefreshTokens.Add(refreshToken);
result.Result.JwtToken = jwtToken;
result.Result.RefreshToken = refreshToken.Token;
result.Result.LastBeamedIn = DateTime.Now;
result.Result.IsBeamedIn = true;
LoggedInAvatar = result.Result;
OASISResult<IAvatar> saveAvatarResult = SaveAvatar(result.Result, autoReplicationMode, autoFailOverMode, autoLoadBalanceMode, waitForAutoReplicationResult);
if (!saveAvatarResult.IsError && saveAvatarResult.IsSaved)
{
result.Result = HideAuthDetails(saveAvatarResult.Result, false, true, false, false);
result.IsSaved = true;
result.Message = "Avatar Successfully Authenticated.";
}
else
OASISErrorHandling.HandleError(ref result, $"Error occured in AuthenticateAsync method in AvatarManager whilst saving the avatar. Reason: {saveAvatarResult.Message}", saveAvatarResult.DetailedMessage);
}
else
result.Result = null;
}
ProviderManager.Instance.SetAndReplaceAutoFailOverListForProviders(currentProviderFailOverList);
//ProviderManager.Instance.IsAutoFailOverEnabled = isAutoFailOverEnabled;
//CLIEngine.SupressConsoleLogging = false;
}
catch (Exception ex)
{
OASISErrorHandling.HandleError(ref result, string.Concat("Unknown error occured in AuthenticateAsync method in AvatarManager. Error Message: ", ex.Message), ex);
result.Result = null;
}
return result;
}
public OASISResult<IAvatar> Register(string avatarTitle, string firstName, string lastName, string email, string password, string username, AvatarType avatarType, OASISType createdOASISType, ConsoleColor cliColour = ConsoleColor.Green, ConsoleColor favColour = ConsoleColor.Green)
{
OASISResult<IAvatar> result = new OASISResult<IAvatar>();
try
{
result = PrepareToRegisterAvatarAsync(avatarTitle, firstName, lastName, email, password, username, avatarType, createdOASISType).Result;
if (result != null && !result.IsError && result.Result != null)
{
// AvatarDetail needs to have the same unique ID as Avatar so the records match (they will have unique/different provider keys per each provider)
OASISResult<IAvatarDetail> avatarDetailResult = PrepareToRegisterAvatarDetail(result.Result.Id, result.Result.Username, result.Result.Email, createdOASISType, cliColour, favColour);
if (avatarDetailResult != null && !avatarDetailResult.IsError && avatarDetailResult.Result != null)
{
OASISResult<IAvatar> saveAvatarResult = SaveAvatar(result.Result);
if (!saveAvatarResult.IsError && saveAvatarResult.IsSaved)
{
result.Result = saveAvatarResult.Result;
OASISResult<IAvatarDetail> saveAvatarDetailResult = SaveAvatarDetail(avatarDetailResult.Result);
if (saveAvatarDetailResult != null && !saveAvatarDetailResult.IsError && saveAvatarDetailResult.Result != null)
result = AvatarRegistered(result);
else
{
result.Message = saveAvatarDetailResult.Message;
result.IsError = saveAvatarDetailResult.IsError;
result.IsSaved = saveAvatarDetailResult.IsSaved;
}
}
else
{
result.Message = saveAvatarResult.Message;
result.IsError = saveAvatarResult.IsError;
result.IsSaved = saveAvatarResult.IsSaved;
}
}
}
}
catch (Exception ex)
{
OASISErrorHandling.HandleError(ref result, string.Concat("Unknown error occured in Register method in AvatarManager. Error Message: ", ex.Message), ex);
result.Result = null;
}
return result;
}
public async Task<OASISResult<IAvatar>> RegisterAsync(string avatarTitle, string firstName, string lastName, string email, string password, string username, AvatarType avatarType, OASISType createdOASISType, ConsoleColor cliColour = ConsoleColor.Green, ConsoleColor favColour = ConsoleColor.Green)
{
OASISResult<IAvatar> result = new OASISResult<IAvatar>();
try
{
result = await PrepareToRegisterAvatarAsync(avatarTitle, firstName, lastName, email, password, username, avatarType, createdOASISType);
if (result != null && !result.IsError && result.Result != null)
{
// AvatarDetail needs to have the same unique ID as Avatar so the records match (they will have unique/different provider keys per each provider)
OASISResult<IAvatarDetail> avatarDetailResult = PrepareToRegisterAvatarDetail(result.Result.Id, result.Result.Username, result.Result.Email, createdOASISType, cliColour, favColour);
if (avatarDetailResult != null && !avatarDetailResult.IsError && avatarDetailResult.Result != null)
{
OASISResult<IAvatar> saveAvatarResult = await SaveAvatarAsync(result.Result);
if (!saveAvatarResult.IsError && saveAvatarResult.IsSaved)
{
result.Result = saveAvatarResult.Result;
OASISResult<IAvatarDetail> saveAvatarDetailResult = await SaveAvatarDetailAsync(avatarDetailResult.Result);
if (saveAvatarDetailResult != null && !saveAvatarDetailResult.IsError && saveAvatarDetailResult.Result != null)
result = AvatarRegistered(result);
else
{
result.Message = saveAvatarDetailResult.Message;
result.IsError = saveAvatarDetailResult.IsError;
result.IsSaved = saveAvatarDetailResult.IsSaved;
}
}
else
{
result.Message = saveAvatarResult.Message;
result.IsError = saveAvatarResult.IsError;
result.IsSaved = saveAvatarResult.IsSaved;
}
}
}
}
catch (Exception ex)
{
OASISErrorHandling.HandleError(ref result, string.Concat("Unknown error occured in RegisterAsync method in AvatarManager. Error Message: ", ex.Message), ex);
result.Result = null;
}
return result;
}
public async Task<OASISResult<IAvatar>> RegisterAdminAsync(string adminFirstName, string adminLastName, string adminEmail, string adminUsername, string adminPassword, OASISType createdOASISType = OASISType.OASISBootLoader, ConsoleColor cliColour = ConsoleColor.Red, ConsoleColor favColour = ConsoleColor.Red, string avatarTitle = "Admin", AvatarType avatarType = AvatarType.Admin)
{
OASISResult<IAvatar> result = new OASISResult<IAvatar>();
try
{
// First try by username...
result = await LoadAvatarAsync(adminUsername, false, false);
if (result.Result == null)
{
// Now try by email...
result = await LoadAvatarByEmailAsync(adminEmail, false, false);
}
if (result.Result != null)
{
result.Message = "Avatar already exists.";
result.IsError = false;
return result;
}
result = await PrepareToRegisterAvatarAsync(avatarTitle, adminFirstName, adminLastName, adminEmail, adminPassword, adminUsername, avatarType, createdOASISType);
if (result != null && !result.IsError && result.Result != null)
{
// Manually verify and activate the admin account immediately
result.Result.Verified = DateTime.Now;
result.Result.IsActive = true;
result.Result.VerificationToken = null; // Clear token as it's already verified
// AvatarDetail needs to have the same unique ID as Avatar so the records match (they will have unique/different provider keys per each provider)
OASISResult<IAvatarDetail> avatarDetailResult = PrepareToRegisterAvatarDetail(result.Result.Id, result.Result.Username, result.Result.Email, createdOASISType, cliColour, favColour);
if (avatarDetailResult != null && !avatarDetailResult.IsError && avatarDetailResult.Result != null)
{
OASISResult<IAvatar> saveAvatarResult = await SaveAvatarAsync(result.Result);
if (!saveAvatarResult.IsError && saveAvatarResult.IsSaved)
{
result.Result = saveAvatarResult.Result;
OASISResult<IAvatarDetail> saveAvatarDetailResult = await SaveAvatarDetailAsync(avatarDetailResult.Result);
if (saveAvatarDetailResult != null && !saveAvatarDetailResult.IsError && saveAvatarDetailResult.Result != null)
{
// result = AvatarRegistered(result); // Don't call this as it sends verification email!
result.Result = HideAuthDetails(result.Result);
result.IsSaved = true;
result.Message = "Admin Account Created Successfully.";
}
else
{
result.Message = saveAvatarDetailResult.Message;
result.IsError = saveAvatarDetailResult.IsError;
result.IsSaved = saveAvatarDetailResult.IsSaved;
}
}
else
{
result.Message = saveAvatarResult.Message;
result.IsError = saveAvatarResult.IsError;
result.IsSaved = saveAvatarResult.IsSaved;
}
}
}
}
catch (Exception ex)
{
OASISErrorHandling.HandleError(ref result, string.Concat("Unknown error occured in RegisterAdminAsync method in AvatarManager. Error Message: ", ex.Message), ex);
result.Result = null;
}
return result;
}
public OASISResult<IAvatar> BeamOut(IAvatar avatar, AutoReplicationMode autoReplicationMode = AutoReplicationMode.UseGlobalDefaultInOASISDNA, AutoFailOverMode autoFailOverMode = AutoFailOverMode.UseGlobalDefaultInOASISDNA, AutoLoadBalanceMode autoLoadBalanceMode = AutoLoadBalanceMode.UseGlobalDefaultInOASISDNA, bool waitForAutoReplicationResult = false, ProviderType providerType = ProviderType.Default)
{
OASISResult<IAvatar> result = new OASISResult<IAvatar>();
avatar.LastBeamedOut = DateTime.Now;
result = SaveAvatar(avatar, autoReplicationMode, autoFailOverMode, autoLoadBalanceMode, waitForAutoReplicationResult, providerType);
return result;
}
public async Task<OASISResult<IAvatar>> BeamOutAsync(IAvatar avatar, AutoReplicationMode autoReplicationMode = AutoReplicationMode.UseGlobalDefaultInOASISDNA, AutoFailOverMode autoFailOverMode = AutoFailOverMode.UseGlobalDefaultInOASISDNA, AutoLoadBalanceMode autoLoadBalanceMode = AutoLoadBalanceMode.UseGlobalDefaultInOASISDNA, bool waitForAutoReplicationResult = false, ProviderType providerType = ProviderType.Default)
{
OASISResult<IAvatar> result = new OASISResult<IAvatar>();
avatar.LastBeamedOut = DateTime.Now;
result = await SaveAvatarAsync(avatar, autoReplicationMode, autoFailOverMode, autoLoadBalanceMode, waitForAutoReplicationResult, providerType);
return result;
}
public OASISResult<bool> VerifyEmail(string token)
{
OASISResult<bool> result = new OASISResult<bool>();
try
{
//TODO: PERFORMANCE} Implement in Providers so more efficient and do not need to return whole list!
OASISResult<IEnumerable<IAvatar>> avatarsResult = LoadAllAvatars(false, false);
if (!avatarsResult.IsError && avatarsResult.Result != null)
{
IAvatar avatar = avatarsResult.Result.FirstOrDefault(x => x.VerificationToken == token);
if (avatar == null)
{
result.Result = false;
result.IsError = true;
result.Message = "Verification Failed";
}
else
{
result.Result = true;
avatar.Verified = DateTime.UtcNow;
avatar.VerificationToken = null;
avatar.IsActive = true;
OASISResult<IAvatar> saveAvatarResult = SaveAvatar(avatar);
result.IsError = saveAvatarResult.IsError;
result.IsSaved = saveAvatarResult.IsSaved;
result.Message = saveAvatarResult.Message;
}
}
else
OASISErrorHandling.HandleError(ref result, $"Error in VerifyEmail loading all avatars. Reason: {avatarsResult.Message}", avatarsResult.DetailedMessage);
if (!result.IsError && result.IsSaved)
{
result.Message = "Verification successful, you can now login";
result.Result = true;
}
else
result.Result = false;
}
catch (Exception ex)
{
OASISErrorHandling.HandleError(ref result, string.Concat("Unknown error occured in VerifyEmail method in AvatarManager. Error Message: ", ex.Message), ex);
result.Result = false;
}
return result;
}
//public async Task<OASISResult<string>> ForgotPassword(ForgotPasswordRequest model)
public async Task<OASISResult<string>> ForgotPasswordAsync(string email, ProviderType providerType = ProviderType.Default)
{
var response = new OASISResult<string>();
try
{
OASISResult<IAvatar> avatarResult = await LoadAvatarByEmailAsync(email, false, false, providerType);
// always return ok response to prevent email enumeration
if (avatarResult.IsError || avatarResult.Result == null)
{
OASISErrorHandling.HandleError(ref response, $"Error occured loading avatar in ForgotPassword, avatar not found. Reason: {avatarResult.Message}", avatarResult.DetailedMessage);
return response;
}
// create reset token that expires after 1 day
avatarResult.Result.ResetToken = RandomTokenString();
avatarResult.Result.ResetTokenExpires = DateTime.UtcNow.AddDays(24);
var saveAvatar = SaveAvatar(avatarResult.Result, providerType: providerType);
if (saveAvatar.IsError)
{
OASISErrorHandling.HandleError(ref response, $"An error occured saving the avatar in ForgotPassword method in AvatarService. Reason: {saveAvatar.Message}", saveAvatar.DetailedMessage);
return response;
}
// send email
SendPasswordResetEmail(avatarResult.Result);
response.Message = "Please check your email for password reset instructions";
response.Result = response.Message;
}
catch (Exception e)
{
response.Exception = e;
OASISErrorHandling.HandleError(ref response, $"An error occured in ForgotPassword method in AvatarService. Reason: {e.Message}");
}
return response;
}
public OASISResult<string> ForgotPassword(string email, ProviderType providerType = ProviderType.Default)
{
var response = new OASISResult<string>();
try
{
OASISResult<IAvatar> avatarResult = LoadAvatarByEmail(email, false, false, providerType);
// always return ok response to prevent email enumeration
if (avatarResult.IsError || avatarResult.Result == null)
{
OASISErrorHandling.HandleError(ref response, $"Error occured loading avatar in ForgotPassword, avatar not found. Reason: {avatarResult.Message}", avatarResult.DetailedMessage);
return response;
}
// create reset token that expires after 1 day
avatarResult.Result.ResetToken = RandomTokenString();
avatarResult.Result.ResetTokenExpires = DateTime.UtcNow.AddDays(24);
var saveAvatar = SaveAvatar(avatarResult.Result, providerType: providerType);
if (saveAvatar.IsError)
{
OASISErrorHandling.HandleError(ref response, $"An error occured saving the avatar in ForgotPassword method in AvatarService. Reason: {saveAvatar.Message}", saveAvatar.DetailedMessage);
return response;
}
// send email
SendPasswordResetEmail(avatarResult.Result);
response.Message = "Please check your email for password reset instructions";
response.Result = response.Message;
}
catch (Exception e)
{
response.Exception = e;
OASISErrorHandling.HandleError(ref response, $"An error occured in ForgotPassword method in AvatarService. Reason: {e.Message}");
}
return response;
}
public async Task<OASISResult<string>> ResetPasswordAsync(string token, string oldPassword, string newPassword, ProviderType providerType = ProviderType.Default)
{
var response = new OASISResult<string>();
try
{
OASISResult<IEnumerable<IAvatar>> avatarsResult = await LoadAllAvatarsAsync(false, false, false, providerType);
if (!avatarsResult.IsError && avatarsResult.Result != null)
{
//TODO: PERFORMANCE} Implement in Providers so more efficient and do not need to return whole list!
var avatar = avatarsResult.Result.FirstOrDefault(x =>
x.ResetToken == token &&
x.ResetTokenExpires > DateTime.UtcNow);
if (avatar == null)
{
OASISErrorHandling.HandleError(ref response, "Avatar not found, token is invalid.");
return response;
}
if (!BCrypt.Net.BCrypt.Verify(oldPassword, avatar.Password))
{
OASISErrorHandling.HandleError(ref response, "Old Password Is Not Correct");
return response;
}
// update password and remove reset token
avatar.Password = BCrypt.Net.BCrypt.HashPassword(newPassword);
avatar.PasswordReset = DateTime.UtcNow;
avatar.ResetToken = null;
avatar.ResetTokenExpires = null;
var saveAvatarResult = await SaveAvatarAsync(avatar, providerType: providerType);
if (saveAvatarResult.IsError)
{
OASISErrorHandling.HandleError(ref saveAvatarResult, $"Error occured in ResetPassword saving the avatar. Reason: {saveAvatarResult.Message}", saveAvatarResult.DetailedMessage);
return response;
}
if (_loggedInAvatar.Id == avatar.Id)
_loggedInAvatar = avatar;
response.Message = "Password reset successful, you can now login";
response.Result = response.Message;
}
else
OASISErrorHandling.HandleError(ref response, $"Error occured in ResetPassword loading all avatars. Reason: {avatarsResult.Message}", avatarsResult.DetailedMessage);
}
catch (Exception e)
{
response.Exception = e;
response.Message = e.Message;
response.IsError = true;
response.IsSaved = false;
OASISErrorHandling.HandleError(ref response, e.Message);
}
return response;
}
public OASISResult<string> ResetPassword(string token, string oldPassword, string newPassword, ProviderType providerType = ProviderType.Default)
{
var response = new OASISResult<string>();
try
{
OASISResult<IEnumerable<IAvatar>> avatarsResult = LoadAllAvatars(false, false, false, providerType);
if (!avatarsResult.IsError && avatarsResult.Result != null)
{
//TODO: PERFORMANCE} Implement in Providers so more efficient and do not need to return whole list!
var avatar = avatarsResult.Result.FirstOrDefault(x =>
x.ResetToken == token &&
x.ResetTokenExpires > DateTime.UtcNow);
if (avatar == null)
{
OASISErrorHandling.HandleError(ref response, "Avatar not found, token is invalid.");
return response;
}
if (!BCrypt.Net.BCrypt.Verify(oldPassword, avatar.Password))
{
OASISErrorHandling.HandleError(ref response, "Old Password Is Not Correct");
return response;
}
// update password and remove reset token
avatar.Password = BCrypt.Net.BCrypt.HashPassword(newPassword);
avatar.PasswordReset = DateTime.UtcNow;
avatar.ResetToken = null;
avatar.ResetTokenExpires = null;
var saveAvatarResult = SaveAvatar(avatar, providerType: providerType);
if (saveAvatarResult.IsError)
{
OASISErrorHandling.HandleError(ref saveAvatarResult, $"Error occured in ResetPassword saving the avatar. Reason: {saveAvatarResult.Message}", saveAvatarResult.DetailedMessage);
return response;
}
response.Message = "Password reset successful, you can now login";
response.Result = response.Message;
}
else
OASISErrorHandling.HandleError(ref response, $"Error occured in ResetPassword loading all avatars. Reason: {avatarsResult.Message}", avatarsResult.DetailedMessage);
}
catch (Exception e)
{
response.Exception = e;
response.Message = e.Message;
response.IsError = true;
response.IsSaved = false;
OASISErrorHandling.HandleError(ref response, e.Message);
}
return response;
}
public string RandomTokenString()
{
using var rngCryptoServiceProvider = new System.Security.Cryptography.RNGCryptoServiceProvider();
var randomBytes = new byte[40];
rngCryptoServiceProvider.GetBytes(randomBytes);
// convert random bytes to hex string
return BitConverter.ToString(randomBytes).Replace("-", "");
}
//TODO: Finish moving Update methods and ALL AvatarService methods here ASAP!
//Update also needs to be able to update ANY avatar property, currently it is only email, name, etc.
/*
public async Task<OASISResult<IAvatar>> Update(Guid id, UpdateRequest avatar)
{
var response = new OASISResult<IAvatar>();
string errorMessage = "Error in Update method in Avatar Service. Reason: ";
try
{
response = await AvatarManager.LoadAvatarAsync(id, false);
if (response.IsError || response.Result == null)
OASISErrorHandling.HandleError(ref response, $"{errorMessage}{response.Message}", response.DetailedMessage);
else
response = await Update(response.Result, avatar);
}
catch (Exception ex)
{
OASISErrorHandling.HandleError(ref response, $"{errorMessage}Unknown Error Occured. See DetailedMessage for more info.", ex.Message, ex);
}
return response;
}
public async Task<OASISResult<IAvatar>> UpdateByEmail(string email, UpdateRequest avatar)
{
var response = new OASISResult<IAvatar>();
string errorMessage = "Error in UpdateByEmail method in Avatar Service. Reason: ";
try
{
response = await AvatarManager.LoadAvatarByEmailAsync(email);
if (response.IsError || response.Result == null)
OASISErrorHandling.HandleError(ref response, $"{errorMessage}{response.Message}", response.DetailedMessage);
else
response = await Update(response.Result, avatar);
}
catch (Exception ex)
{
OASISErrorHandling.HandleError(ref response, $"{errorMessage}Unknown Error Occured. See DetailedMessage for more info.", ex.Message, ex);
}
return response;
}
public async Task<OASISResult<IAvatar>> UpdateByUsername(string username, UpdateRequest avatar)
{
var response = new OASISResult<IAvatar>();
string errorMessage = "Error in UpdateByUsername method in Avatar Service. Reason: ";
try
{
response = await AvatarManager.LoadAvatarAsync(username);
if (response.IsError || response.Result == null)
OASISErrorHandling.HandleError(ref response, $"{errorMessage}{response.Message}", response.DetailedMessage);
else
response = await Update(response.Result, avatar);
}
catch (Exception ex)
{
OASISErrorHandling.HandleError(ref response, $"{errorMessage}Unknown Error Occured. See DetailedMessage for more info.", ex.Message, ex);
}
return response;
}*/
public OASISResult<bool> CheckIfEmailIsAlreadyInUse(string email, bool sendMail = true)
{
OASISResult<bool> result = new OASISResult<bool>();
//Temp supress logging to the console in case STAR CLI is creating a new avatar...
//CLIEngine.SupressConsoleLogging = true;
//Temp disable the OASIS HyperDrive so it returns fast and does not attempt to find the avatar across all providers! ;-)
//TODO: May want to fine tune how we handle this in future?
//bool isAutoFailOverEnabled = ProviderManager.Instance.IsAutoFailOverEnabled;
//ProviderManager.Instance.IsAutoFailOverEnabled = false;
List<EnumValue<ProviderType>> currentProviderFailOverList = ProviderManager.Instance.GetProviderAutoFailOverList();
ProviderManager.Instance.SetAndReplaceAutoFailOverListForProviders(ProviderManager.Instance.GetProviderAutoFailOverListForCheckIfEmailAlreadyInUse());
OASISResult<IAvatar> existingAvatarResult = LoadAvatarByEmail(email);
ProviderManager.Instance.SetAndReplaceAutoFailOverListForProviders(currentProviderFailOverList);
//ProviderManager.Instance.IsAutoFailOverEnabled = isAutoFailOverEnabled;
//CLIEngine.SupressConsoleLogging = false;
if (!existingAvatarResult.IsError && existingAvatarResult.Result != null)
{
//If the avatar has previously been deleted (soft deleted) then allow them to create a new avatar with the same email address.
if (existingAvatarResult.Result.DeletedDate != DateTime.MinValue)
{
result.Result = true;
OASISErrorHandling.HandleError(ref result, $"The avatar using email {email} was deleted on {existingAvatarResult.Result.DeletedDate} by avatar with id {existingAvatarResult.Result.DeletedByAvatarId}, please contact support (to either restore your old avatar or permanently delete your old avatar so you can then re-use your old email address to create a new avatar) or create a new avatar with a new email address.");
}
else
{
result.Result = true;
OASISErrorHandling.HandleError(ref result, $"Sorry, the email {email} is already in use, please use another one.");
}
}
else
result.Message = $"Email {email} not in use.";
if (result.Result && sendMail)
SendAlreadyRegisteredEmail(email, result.Message);
return result;
}
public OASISResult<bool> CheckIfUsernameIsAlreadyInUse(string username)
{
OASISResult<bool> result = new OASISResult<bool>();
////Temp supress logging to the console in case STAR CLI is creating a new avatar...
//CLIEngine.SupressConsoleLogging = true;
//Temp disable the OASIS HyperDrive so it returns fast and does not attempt to find the avatar across all providers! ;-)
//TODO: May want to fine tune how we handle this in future?
//bool isAutoFailOverEnabled = ProviderManager.Instance.IsAutoFailOverEnabled;
//ProviderManager.Instance.IsAutoFailOverEnabled = false;
List<EnumValue<ProviderType>> currentProviderFailOverList = ProviderManager.Instance.GetProviderAutoFailOverList();
ProviderManager.Instance.SetAndReplaceAutoFailOverListForProviders(ProviderManager.Instance.GetProviderAutoFailOverListForCheckIfUsernameAlreadyInUse());
OASISResult<IAvatar> existingAvatarResult = LoadAvatar(username);
ProviderManager.Instance.SetAndReplaceAutoFailOverListForProviders(currentProviderFailOverList);
//ProviderManager.Instance.IsAutoFailOverEnabled = isAutoFailOverEnabled;
//CLIEngine.SupressConsoleLogging = false;
if (!existingAvatarResult.IsError && existingAvatarResult.Result != null)
{
//If the avatar has previously been deleted (soft deleted) then allow them to create a new avatar with the same email address.
if (existingAvatarResult.Result.DeletedDate != DateTime.MinValue)
{
result.Result = true;
OASISErrorHandling.HandleError(ref result, $"The avatar using username {username} was deleted on {existingAvatarResult.Result.DeletedDate} by avatar with id {existingAvatarResult.Result.DeletedByAvatarId}, please contact support (to either restore your old avatar or permanently delete your old avatar so you can then re-use your old email address to create a new avatar) or create a new avatar with a new email address.");
}
else
{
result.Result = true;
OASISErrorHandling.HandleError(ref result, $"Sorry, the username {username} is already in use, please use another one.");
}
}
else
result.Message = $"Username {username} not in use.";
return result;
}
//public IAvatar HideAuthDetails(IAvatar avatar, bool hidePassword = true, bool hidePrivateKeys = true, bool hideVerificationToken = true, bool hideRefreshTokens = true)
public IAvatar HideAuthDetails(IAvatar avatar, bool hidePassword = false, bool hidePrivateKeys = true, bool hideVerificationToken = false, bool hideRefreshTokens = false)
{
if (OASISDNA.OASIS.Security.HideVerificationToken || hideVerificationToken)
avatar.VerificationToken = null;
if (hidePassword)
avatar.Password = null;
if (hidePrivateKeys)
{
foreach (ProviderType providerType in avatar.ProviderWallets.Keys)
{
foreach (ProviderWallet wallet in avatar.ProviderWallets[providerType])
wallet.PrivateKey = null;
}
}
if (OASISDNA.OASIS.Security.HideRefreshTokens || hideRefreshTokens)
avatar.RefreshTokens = null;
return avatar;
}
public IEnumerable<IAvatar> HideAuthDetails(IEnumerable<IAvatar> avatars)
{
List<IAvatar> tempList = avatars.ToList();
for (int i = 0; i < tempList.Count; i++)
tempList[i] = HideAuthDetails(tempList[i]);
return tempList;
}
public async Task<OASISResult<IAvatarDetail>> SaveAvatarDetailForProviderAsync(IAvatarDetail avatar, OASISResult<IAvatarDetail> result, SaveMode saveMode, ProviderType providerType = ProviderType.Default)
{
string errorMessageTemplate = "Error in SaveAvatarDetailForProviderAsync method in AvatarManager saving avatar detail with name {0}, username {1} and id {2} for provider {3} for {4}. Reason: ";
string errorMessage = string.Format(errorMessageTemplate, avatar.Name, avatar.Username, avatar.Id, providerType, Enum.GetName(typeof(SaveMode), saveMode));
try
{
OASISResult<IOASISStorageProvider> providerResult = await ProviderManager.Instance.SetAndActivateCurrentStorageProviderAsync(providerType);
errorMessage = string.Format(errorMessageTemplate, avatar.Name, avatar.Username, avatar.Id, ProviderManager.Instance.CurrentStorageProviderType.Name, Enum.GetName(typeof(SaveMode), saveMode));
if (!providerResult.IsError && providerResult.Result != null)
{
var task = providerResult.Result.SaveAvatarDetailAsync(avatar);
if (await Task.WhenAny(task, Task.Delay(OASISDNA.OASIS.StorageProviders.ProviderMethodCallTimeOutSeconds * 1000)) == task)
{
if (task.Result == null || (task.Result.IsError || task.Result.Result == null))
{
if (task.Result == null || (task.Result != null && string.IsNullOrEmpty(task.Result.Message) && saveMode != SaveMode.AutoReplication))
task.Result.Message = "Unknown.";
OASISErrorHandling.HandleWarning(ref result, string.Concat(errorMessage, task.Result.Message), task.Result.DetailedMessage, saveMode == SaveMode.AutoReplication);
}
else
{
result.IsSaved = true;
result.Result = task.Result.Result;
}
}
else
OASISErrorHandling.HandleWarning(ref result, string.Concat(errorMessage, "timeout occured."), saveMode == SaveMode.AutoReplication);
}
else
OASISErrorHandling.HandleWarning(ref result, string.Concat(errorMessage, providerResult.Message), providerResult.DetailedMessage, saveMode == SaveMode.AutoReplication);
}
catch (Exception ex)
{
OASISErrorHandling.HandleWarning(ref result, string.Concat(errorMessage, ex.Message), ex, saveMode == SaveMode.AutoReplication);
}
return result;
}
public OASISResult<IAvatarDetail> SaveAvatarDetailForProvider(IAvatarDetail avatar, OASISResult<IAvatarDetail> result, SaveMode saveMode, ProviderType providerType = ProviderType.Default)
{
return SaveAvatarDetailForProviderAsync(avatar, result, saveMode, providerType).Result;
}
public OASISResult<bool> DeleteAvatarForProvider(Guid id, OASISResult<bool> result, SaveMode saveMode, bool softDelete = true, ProviderType providerType = ProviderType.Default)
{
return DeleteAvatarForProviderAsync(id, result, saveMode, softDelete, providerType).Result;
}
public async Task<OASISResult<bool>> DeleteAvatarForProviderAsync(Guid id, OASISResult<bool> result, SaveMode saveMode, bool softDelete = true, ProviderType providerType = ProviderType.Default)
{
string errorMessageTemplate = "Error in DeleteAvatarForProviderAsync method in AvatarManager deleting avatar with email {0} for provider {1} for {2}. Reason: ";
string errorMessage = string.Format(errorMessageTemplate, id, providerType, Enum.GetName(typeof(SaveMode), saveMode));
try
{
OASISResult<IOASISStorageProvider> providerResult = await ProviderManager.Instance.SetAndActivateCurrentStorageProviderAsync(providerType);
errorMessage = string.Format(errorMessageTemplate, id, ProviderManager.Instance.CurrentStorageProviderType.Name, Enum.GetName(typeof(SaveMode), saveMode));
if (!providerResult.IsError && providerResult.Result != null)
{
var task = providerResult.Result.DeleteAvatarAsync(id, softDelete);
if (await Task.WhenAny(task, Task.Delay(OASISDNA.OASIS.StorageProviders.ProviderMethodCallTimeOutSeconds * 1000)) == task)
{
if (task.Result.IsError || !task.Result.Result)
{
if (string.IsNullOrEmpty(task.Result.Message) && saveMode != SaveMode.AutoReplication)
result.Message = "Unknown.";
OASISErrorHandling.HandleWarning(ref result, string.Concat(errorMessage, task.Result.Message), task.Result.DetailedMessage, saveMode == SaveMode.AutoReplication);
}
else
{
result.IsSaved = true;
result.Result = task.Result.Result;
}
}
else
OASISErrorHandling.HandleWarning(ref result, string.Concat(errorMessage, "timeout occured."), saveMode == SaveMode.AutoReplication);
}
else
OASISErrorHandling.HandleWarning(ref result, string.Concat(errorMessage, providerResult.Message), providerResult.DetailedMessage, saveMode == SaveMode.AutoReplication);
}
catch (Exception ex)
{