-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
AbpUserStore.cs
1303 lines (1066 loc) · 64.8 KB
/
AbpUserStore.cs
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.Globalization;
using System.Linq;
using System.Security.Claims;
using System.Threading;
using System.Threading.Tasks;
using System.Transactions;
using Abp.Authorization.Roles;
using Abp.Dependency;
using Abp.Domain.Repositories;
using Abp.Domain.Uow;
using Abp.Extensions;
using Abp.Linq;
using Abp.Runtime.Session;
using Abp.Zero;
using Castle.Core.Logging;
using JetBrains.Annotations;
using Microsoft.AspNetCore.Identity;
namespace Abp.Authorization.Users
{
/// <summary>
/// Represents a new instance of a persistence store for the specified user and role types.
/// </summary>
public class AbpUserStore<TRole, TUser> :
IUserLoginStore<TUser>,
IUserRoleStore<TUser>,
IUserClaimStore<TUser>,
IUserPasswordStore<TUser>,
IUserSecurityStampStore<TUser>,
IUserEmailStore<TUser>,
IUserLockoutStore<TUser>,
IUserPhoneNumberStore<TUser>,
IUserTwoFactorStore<TUser>,
IUserAuthenticationTokenStore<TUser>,
IUserPermissionStore<TUser>,
IQueryableUserStore<TUser>,
IUserAuthenticatorKeyStore<TUser>,
ITransientDependency
where TRole : AbpRole<TUser>
where TUser : AbpUser<TUser>
{
public ILogger Logger { get; set; }
/// <summary>
/// Gets or sets the <see cref="IdentityErrorDescriber"/> for any error that occurred with the current operation.
/// </summary>
public IdentityErrorDescriber ErrorDescriber { get; set; }
/// <summary>
/// Gets or sets a flag indicating if changes should be persisted after CreateAsync, UpdateAsync and DeleteAsync are called.
/// </summary>
/// <value>
/// True if changes should be automatically persisted, otherwise false.
/// </value>
public bool AutoSaveChanges { get; set; } = true;
public IAbpSession AbpSession { get; set; }
public IQueryable<TUser> Users => UserRepository.GetAll();
public IRepository<TUser, long> UserRepository { get; }
private readonly IRepository<TRole> _roleRepository;
private readonly IRepository<UserRole, long> _userRoleRepository;
private readonly IAsyncQueryableExecuter _asyncQueryableExecuter;
private readonly IRepository<UserLogin, long> _userLoginRepository;
private readonly IRepository<UserClaim, long> _userClaimRepository;
private readonly IRepository<UserPermissionSetting, long> _userPermissionSettingRepository;
private readonly IUnitOfWorkManager _unitOfWorkManager;
public AbpUserStore(
IUnitOfWorkManager unitOfWorkManager,
IRepository<TUser, long> userRepository,
IRepository<TRole> roleRepository,
IAsyncQueryableExecuter asyncQueryableExecuter,
IRepository<UserRole, long> userRoleRepository,
IRepository<UserLogin, long> userLoginRepository,
IRepository<UserClaim, long> userClaimRepository,
IRepository<UserPermissionSetting, long> userPermissionSettingRepository)
{
_unitOfWorkManager = unitOfWorkManager;
UserRepository = userRepository;
_roleRepository = roleRepository;
_asyncQueryableExecuter = asyncQueryableExecuter;
_userRoleRepository = userRoleRepository;
_userLoginRepository = userLoginRepository;
_userClaimRepository = userClaimRepository;
_userPermissionSettingRepository = userPermissionSettingRepository;
AbpSession = NullAbpSession.Instance;
ErrorDescriber = new IdentityErrorDescriber();
Logger = NullLogger.Instance;
}
/// <summary>Saves the current store.</summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
/// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns>
protected Task SaveChanges(CancellationToken cancellationToken)
{
if (!AutoSaveChanges || _unitOfWorkManager.Current == null)
{
return Task.CompletedTask;
}
return _unitOfWorkManager.Current.SaveChangesAsync();
}
/// <summary>
/// Gets the user identifier for the specified <paramref name="user"/>.
/// </summary>
/// <param name="user">The user whose identifier should be retrieved.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
/// <returns>The <see cref="Task"/> that represents the asynchronous operation, containing the identifier for the specified <paramref name="user"/>.</returns>
public virtual Task<string> GetUserIdAsync([NotNull] TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
Check.NotNull(user, nameof(user));
return Task.FromResult(user.Id.ToString());
}
/// <summary>
/// Gets the user name for the specified <paramref name="user"/>.
/// </summary>
/// <param name="user">The user whose name should be retrieved.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
/// <returns>The <see cref="Task"/> that represents the asynchronous operation, containing the name for the specified <paramref name="user"/>.</returns>
public virtual Task<string> GetUserNameAsync([NotNull] TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
Check.NotNull(user, nameof(user));
return Task.FromResult(user.UserName);
}
/// <summary>
/// Sets the given <paramref name="userName" /> for the specified <paramref name="user"/>.
/// </summary>
/// <param name="user">The user whose name should be set.</param>
/// <param name="userName">The user name to set.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
/// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns>
public virtual Task SetUserNameAsync([NotNull] TUser user, string userName, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
Check.NotNull(user, nameof(user));
user.UserName = userName;
return Task.CompletedTask;
}
/// <summary>
/// Gets the normalized user name for the specified <paramref name="user"/>.
/// </summary>
/// <param name="user">The user whose normalized name should be retrieved.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
/// <returns>The <see cref="Task"/> that represents the asynchronous operation, containing the normalized user name for the specified <paramref name="user"/>.</returns>
public virtual Task<string> GetNormalizedUserNameAsync([NotNull] TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
Check.NotNull(user, nameof(user));
return Task.FromResult(user.NormalizedUserName);
}
/// <summary>
/// Sets the given normalized name for the specified <paramref name="user"/>.
/// </summary>
/// <param name="user">The user whose name should be set.</param>
/// <param name="normalizedName">The normalized name to set.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
/// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns>
public virtual Task SetNormalizedUserNameAsync([NotNull] TUser user, string normalizedName, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
Check.NotNull(user, nameof(user));
user.NormalizedUserName = normalizedName;
return Task.CompletedTask;
}
/// <summary>
/// Creates the specified <paramref name="user"/> in the user store.
/// </summary>
/// <param name="user">The user to create.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
/// <returns>The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/> of the creation operation.</returns>
public virtual async Task<IdentityResult> CreateAsync([NotNull] TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
Check.NotNull(user, nameof(user));
await UserRepository.InsertAsync(user);
await SaveChanges(cancellationToken);
return IdentityResult.Success;
}
/// <summary>
/// Updates the specified <paramref name="user"/> in the user store.
/// </summary>
/// <param name="user">The user to update.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
/// <returns>The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/> of the update operation.</returns>
public virtual async Task<IdentityResult> UpdateAsync([NotNull] TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
Check.NotNull(user, nameof(user));
user.ConcurrencyStamp = Guid.NewGuid().ToString();
await UserRepository.UpdateAsync(user);
try
{
await SaveChanges(cancellationToken);
}
catch (AbpDbConcurrencyException ex)
{
Logger.Warn(ex.ToString(), ex);
return IdentityResult.Failed(ErrorDescriber.ConcurrencyFailure());
}
await SaveChanges(cancellationToken);
return IdentityResult.Success;
}
/// <summary>
/// Deletes the specified <paramref name="user"/> from the user store.
/// </summary>
/// <param name="user">The user to delete.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
/// <returns>The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/> of the update operation.</returns>
public virtual async Task<IdentityResult> DeleteAsync([NotNull] TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
Check.NotNull(user, nameof(user));
await UserRepository.DeleteAsync(user);
try
{
await SaveChanges(cancellationToken);
}
catch (AbpDbConcurrencyException ex)
{
Logger.Warn(ex.ToString(), ex);
return IdentityResult.Failed(ErrorDescriber.ConcurrencyFailure());
}
await SaveChanges(cancellationToken);
return IdentityResult.Success;
}
/// <summary>
/// Finds and returns a user, if any, who has the specified <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The user ID to search for.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
/// <returns>
/// The <see cref="Task"/> that represents the asynchronous operation, containing the user matching the specified <paramref name="userId"/> if it exists.
/// </returns>
public virtual Task<TUser> FindByIdAsync(string userId, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
return UserRepository.FirstOrDefaultAsync(userId.To<long>());
}
/// <summary>
/// Finds and returns a user, if any, who has the specified normalized user name.
/// </summary>
/// <param name="normalizedUserName">The normalized user name to search for.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
/// <returns>
/// The <see cref="Task"/> that represents the asynchronous operation, containing the user matching the specified <paramref name="normalizedUserName"/> if it exists.
/// </returns>
public virtual Task<TUser> FindByNameAsync([NotNull] string normalizedUserName, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
Check.NotNull(normalizedUserName, nameof(normalizedUserName));
return UserRepository.FirstOrDefaultAsync(u => u.NormalizedUserName == normalizedUserName);
}
/// <summary>
/// Sets the password hash for a user.
/// </summary>
/// <param name="user">The user to set the password hash for.</param>
/// <param name="passwordHash">The password hash to set.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
/// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns>
public virtual Task SetPasswordHashAsync([NotNull] TUser user, string passwordHash, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
Check.NotNull(user, nameof(user));
user.Password = passwordHash;
return Task.CompletedTask;
}
/// <summary>
/// Gets the password hash for a user.
/// </summary>
/// <param name="user">The user to retrieve the password hash for.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
/// <returns>A <see cref="Task{TResult}"/> that contains the password hash for the user.</returns>
public virtual Task<string> GetPasswordHashAsync([NotNull] TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
Check.NotNull(user, nameof(user));
return Task.FromResult(user.Password);
}
/// <summary>
/// Returns a flag indicating if the specified user has a password.
/// </summary>
/// <param name="user">The user to retrieve the password hash for.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
/// <returns>A <see cref="Task{TResult}"/> containing a flag indicating if the specified user has a password. If the
/// user has a password the returned value with be true, otherwise it will be false.</returns>
public virtual Task<bool> HasPasswordAsync([NotNull] TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
Check.NotNull(user, nameof(user));
return Task.FromResult(user.Password != null);
}
/// <summary>
/// Adds the given <paramref name="normalizedRoleName"/> to the specified <paramref name="user"/>.
/// </summary>
/// <param name="user">The user to add the role to.</param>
/// <param name="normalizedRoleName">The role to add.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
/// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns>
public virtual async Task AddToRoleAsync([NotNull] TUser user, [NotNull] string normalizedRoleName, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
Check.NotNull(user, nameof(user));
Check.NotNull(normalizedRoleName, nameof(normalizedRoleName));
if (await IsInRoleAsync(user, normalizedRoleName, cancellationToken))
{
return;
}
var role = await _roleRepository.FirstOrDefaultAsync(r => r.NormalizedName== normalizedRoleName);
if (role == null)
{
throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "Role {0} does not exist!", normalizedRoleName));
}
user.Roles.Add(new UserRole(user.TenantId, user.Id, role.Id));
}
/// <summary>
/// Removes the given <paramref name="normalizedRoleName"/> from the specified <paramref name="user"/>.
/// </summary>
/// <param name="user">The user to remove the role from.</param>
/// <param name="normalizedRoleName">The role to remove.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
/// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns>
public virtual async Task RemoveFromRoleAsync([NotNull] TUser user, [NotNull] string normalizedRoleName, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
Check.NotNull(user, nameof(user));
if (string.IsNullOrWhiteSpace(normalizedRoleName))
{
throw new ArgumentException(nameof(normalizedRoleName) + " can not be null or whitespace");
}
if (!await IsInRoleAsync(user, normalizedRoleName, cancellationToken))
{
return;
}
var role = await _roleRepository.FirstOrDefaultAsync(r => r.NormalizedName == normalizedRoleName);
if (role == null)
{
return;
}
user.Roles.RemoveAll(r => r.RoleId == role.Id);
}
/// <summary>
/// Retrieves the roles the specified <paramref name="user"/> is a member of.
/// </summary>
/// <param name="user">The user whose roles should be retrieved.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
/// <returns>A <see cref="Task{TResult}"/> that contains the roles the user is a member of.</returns>
[UnitOfWork]
public virtual async Task<IList<string>> GetRolesAsync([NotNull] TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
Check.NotNull(user, nameof(user));
var query = from userRole in _userRoleRepository.GetAll()
join role in _roleRepository.GetAll() on userRole.RoleId equals role.Id
where userRole.UserId == user.Id
select role.Name;
return await _asyncQueryableExecuter.ToListAsync(query);
}
/// <summary>
/// Returns a flag indicating if the specified user is a member of the give <paramref name="normalizedRoleName"/>.
/// </summary>
/// <param name="user">The user whose role membership should be checked.</param>
/// <param name="normalizedRoleName">The role to check membership of</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
/// <returns>A <see cref="Task{TResult}"/> containing a flag indicating if the specified user is a member of the given group. If the
/// user is a member of the group the returned value with be true, otherwise it will be false.</returns>
public virtual async Task<bool> IsInRoleAsync([NotNull] TUser user, [NotNull] string normalizedRoleName, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
Check.NotNull(user, nameof(user));
if (string.IsNullOrWhiteSpace(normalizedRoleName))
{
throw new ArgumentException(nameof(normalizedRoleName) + " can not be null or whitespace");
}
var role = await _roleRepository.FirstOrDefaultAsync(r => r.NormalizedName == normalizedRoleName);
if (role == null)
{
return false;
}
await UserRepository.EnsureCollectionLoadedAsync(user, u => u.Roles, cancellationToken);
return user.Roles.Any(r => r.RoleId == role.Id);
}
/// <summary>
/// Dispose the store
/// </summary>
public void Dispose()
{
}
/// <summary>
/// Get the claims associated with the specified <paramref name="user"/> as an asynchronous operation.
/// </summary>
/// <param name="user">The user whose claims should be retrieved.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
/// <returns>A <see cref="Task{TResult}"/> that contains the claims granted to a user.</returns>
public virtual async Task<IList<Claim>> GetClaimsAsync([NotNull] TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
Check.NotNull(user, nameof(user));
await UserRepository.EnsureCollectionLoadedAsync(user, u => u.Claims, cancellationToken);
return user.Claims.Select(c => new Claim(c.ClaimType, c.ClaimValue)).ToList();
}
/// <summary>
/// Adds the <paramref name="claims"/> given to the specified <paramref name="user"/>.
/// </summary>
/// <param name="user">The user to add the claim to.</param>
/// <param name="claims">The claim to add to the user.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
/// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns>
public virtual async Task AddClaimsAsync([NotNull] TUser user, [NotNull] IEnumerable<Claim> claims, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
Check.NotNull(user, nameof(user));
Check.NotNull(claims, nameof(claims));
await UserRepository.EnsureCollectionLoadedAsync(user, u => u.Claims, cancellationToken);
foreach (var claim in claims)
{
user.Claims.Add(new UserClaim(user, claim));
}
}
/// <summary>
/// Replaces the <paramref name="claim"/> on the specified <paramref name="user"/>, with the <paramref name="newClaim"/>.
/// </summary>
/// <param name="user">The user to replace the claim on.</param>
/// <param name="claim">The claim replace.</param>
/// <param name="newClaim">The new claim replacing the <paramref name="claim"/>.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
/// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns>
public virtual async Task ReplaceClaimAsync([NotNull] TUser user, [NotNull] Claim claim, [NotNull] Claim newClaim, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
Check.NotNull(user, nameof(user));
Check.NotNull(claim, nameof(claim));
Check.NotNull(newClaim, nameof(newClaim));
await UserRepository.EnsureCollectionLoadedAsync(user, u => u.Claims, cancellationToken);
var userClaims = user.Claims.Where(uc => uc.ClaimValue == claim.Value && uc.ClaimType == claim.Type);
foreach (var userClaim in userClaims)
{
userClaim.ClaimType = claim.Type;
userClaim.ClaimValue = claim.Value;
}
}
/// <summary>
/// Removes the <paramref name="claims"/> given from the specified <paramref name="user"/>.
/// </summary>
/// <param name="user">The user to remove the claims from.</param>
/// <param name="claims">The claim to remove.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
/// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns>
public virtual async Task RemoveClaimsAsync([NotNull] TUser user, [NotNull] IEnumerable<Claim> claims, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
Check.NotNull(user, nameof(user));
Check.NotNull(claims, nameof(claims));
await UserRepository.EnsureCollectionLoadedAsync(user, u => u.Claims, cancellationToken);
foreach (var claim in claims)
{
user.Claims.RemoveAll(c => c.ClaimValue == claim.Value && c.ClaimType == claim.Type);
}
}
/// <summary>
/// Adds the <paramref name="login"/> given to the specified <paramref name="user"/>.
/// </summary>
/// <param name="user">The user to add the login to.</param>
/// <param name="login">The login to add to the user.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
/// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns>
public virtual async Task AddLoginAsync([NotNull] TUser user, [NotNull] UserLoginInfo login, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
Check.NotNull(user, nameof(user));
Check.NotNull(login, nameof(login));
await UserRepository.EnsureCollectionLoadedAsync(user, u => u.Logins, cancellationToken);
user.Logins.Add(new UserLogin(user.TenantId, user.Id, login.LoginProvider, login.ProviderKey));
}
/// <summary>
/// Removes the <paramref name="loginProvider"/> given from the specified <paramref name="user"/>.
/// </summary>
/// <param name="user">The user to remove the login from.</param>
/// <param name="loginProvider">The login to remove from the user.</param>
/// <param name="providerKey">The key provided by the <paramref name="loginProvider"/> to identify a user.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
/// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns>
public virtual async Task RemoveLoginAsync([NotNull] TUser user, [NotNull] string loginProvider, [NotNull] string providerKey, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
Check.NotNull(user, nameof(user));
Check.NotNull(loginProvider, nameof(loginProvider));
Check.NotNull(providerKey, nameof(providerKey));
await UserRepository.EnsureCollectionLoadedAsync(user, u => u.Logins, cancellationToken);
user.Logins.RemoveAll(userLogin => userLogin.LoginProvider == loginProvider && userLogin.ProviderKey == providerKey);
}
/// <summary>
/// Retrieves the associated logins for the specified <param ref="user"/>.
/// </summary>
/// <param name="user">The user whose associated logins to retrieve.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
/// <returns>
/// The <see cref="Task"/> for the asynchronous operation, containing a list of <see cref="UserLoginInfo"/> for the specified <paramref name="user"/>, if any.
/// </returns>
public virtual async Task<IList<UserLoginInfo>> GetLoginsAsync([NotNull] TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
Check.NotNull(user, nameof(user));
await UserRepository.EnsureCollectionLoadedAsync(user, u => u.Logins, cancellationToken);
return user.Logins.Select(l => new UserLoginInfo(l.LoginProvider, l.ProviderKey, l.LoginProvider)).ToList();
}
/// <summary>
/// Retrieves the user associated with the specified login provider and login provider key..
/// </summary>
/// <param name="loginProvider">The login provider who provided the <paramref name="providerKey"/>.</param>
/// <param name="providerKey">The key provided by the <paramref name="loginProvider"/> to identify a user.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
/// <returns>
/// The <see cref="Task"/> for the asynchronous operation, containing the user, if any which matched the specified login provider and key.
/// </returns>
[UnitOfWork]
public virtual Task<TUser> FindByLoginAsync([NotNull] string loginProvider, [NotNull] string providerKey, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
Check.NotNull(loginProvider, nameof(loginProvider));
Check.NotNull(providerKey, nameof(providerKey));
var query = from userLogin in _userLoginRepository.GetAll()
join user in UserRepository.GetAll() on userLogin.UserId equals user.Id
where userLogin.LoginProvider == loginProvider &&
userLogin.ProviderKey == providerKey &&
userLogin.TenantId == AbpSession.TenantId
select user;
return _asyncQueryableExecuter.FirstOrDefaultAsync(query);
}
/// <summary>
/// Gets a flag indicating whether the email address for the specified <paramref name="user"/> has been verified, true if the email address is verified otherwise
/// false.
/// </summary>
/// <param name="user">The user whose email confirmation status should be returned.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
/// <returns>
/// The task object containing the results of the asynchronous operation, a flag indicating whether the email address for the specified <paramref name="user"/>
/// has been confirmed or not.
/// </returns>
public virtual Task<bool> GetEmailConfirmedAsync([NotNull] TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
Check.NotNull(user, nameof(user));
return Task.FromResult(user.IsEmailConfirmed);
}
/// <summary>
/// Sets the flag indicating whether the specified <paramref name="user"/>'s email address has been confirmed or not.
/// </summary>
/// <param name="user">The user whose email confirmation status should be set.</param>
/// <param name="confirmed">A flag indicating if the email address has been confirmed, true if the address is confirmed otherwise false.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
/// <returns>The task object representing the asynchronous operation.</returns>
public virtual Task SetEmailConfirmedAsync([NotNull] TUser user, bool confirmed, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
Check.NotNull(user, nameof(user));
user.IsEmailConfirmed = confirmed;
return Task.CompletedTask;
}
/// <summary>
/// Sets the <paramref name="email"/> address for a <paramref name="user"/>.
/// </summary>
/// <param name="user">The user whose email should be set.</param>
/// <param name="email">The email to set.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
/// <returns>The task object representing the asynchronous operation.</returns>
public virtual Task SetEmailAsync([NotNull] TUser user, string email, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
Check.NotNull(user, nameof(user));
user.EmailAddress = email;
return Task.CompletedTask;
}
/// <summary>
/// Gets the email address for the specified <paramref name="user"/>.
/// </summary>
/// <param name="user">The user whose email should be returned.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
/// <returns>The task object containing the results of the asynchronous operation, the email address for the specified <paramref name="user"/>.</returns>
public virtual Task<string> GetEmailAsync([NotNull] TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
Check.NotNull(user, nameof(user));
return Task.FromResult(user.EmailAddress);
}
/// <summary>
/// Returns the normalized email for the specified <paramref name="user"/>.
/// </summary>
/// <param name="user">The user whose email address to retrieve.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
/// <returns>
/// The task object containing the results of the asynchronous lookup operation, the normalized email address if any associated with the specified user.
/// </returns>
public virtual Task<string> GetNormalizedEmailAsync([NotNull] TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
Check.NotNull(user, nameof(user));
return Task.FromResult(user.NormalizedEmailAddress);
}
/// <summary>
/// Sets the normalized email for the specified <paramref name="user"/>.
/// </summary>
/// <param name="user">The user whose email address to set.</param>
/// <param name="normalizedEmail">The normalized email to set for the specified <paramref name="user"/>.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
/// <returns>The task object representing the asynchronous operation.</returns>
public virtual Task SetNormalizedEmailAsync([NotNull] TUser user, string normalizedEmail, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
Check.NotNull(user, nameof(user));
user.NormalizedEmailAddress = normalizedEmail;
return Task.CompletedTask;
}
/// <summary>
/// Gets the user, if any, associated with the specified, normalized email address.
/// </summary>
/// <param name="normalizedEmail">The normalized email address to return the user for.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
/// <returns>
/// The task object containing the results of the asynchronous lookup operation, the user if any associated with the specified normalized email address.
/// </returns>
public virtual Task<TUser> FindByEmailAsync(string normalizedEmail, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
return UserRepository.FirstOrDefaultAsync(u => u.NormalizedEmailAddress == normalizedEmail);
}
/// <summary>
/// Gets the last <see cref="DateTimeOffset"/> a user's last lockout expired, if any.
/// Any time in the past should be indicates a user is not locked out.
/// </summary>
/// <param name="user">The user whose lockout date should be retrieved.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
/// <returns>
/// A <see cref="Task{TResult}"/> that represents the result of the asynchronous query, a <see cref="DateTimeOffset"/> containing the last time
/// a user's lockout expired, if any.
/// </returns>
public virtual Task<DateTimeOffset?> GetLockoutEndDateAsync([NotNull] TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
Check.NotNull(user, nameof(user));
if (!user.LockoutEndDateUtc.HasValue)
{
return Task.FromResult<DateTimeOffset?>(null);
}
var lockoutEndDate = DateTime.SpecifyKind(user.LockoutEndDateUtc.Value, DateTimeKind.Utc);
return Task.FromResult<DateTimeOffset?>(new DateTimeOffset(lockoutEndDate));
}
/// <summary>
/// Locks out a user until the specified end date has passed. Setting a end date in the past immediately unlocks a user.
/// </summary>
/// <param name="user">The user whose lockout date should be set.</param>
/// <param name="lockoutEnd">The <see cref="DateTimeOffset"/> after which the <paramref name="user"/>'s lockout should end.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
/// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns>
public virtual Task SetLockoutEndDateAsync([NotNull] TUser user, DateTimeOffset? lockoutEnd, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
Check.NotNull(user, nameof(user));
user.LockoutEndDateUtc = lockoutEnd?.UtcDateTime;
return Task.CompletedTask;
}
/// <summary>
/// Records that a failed access has occurred, incrementing the failed access count.
/// </summary>
/// <param name="user">The user whose cancellation count should be incremented.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
/// <returns>The <see cref="Task"/> that represents the asynchronous operation, containing the incremented failed access count.</returns>
public virtual Task<int> IncrementAccessFailedCountAsync([NotNull] TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
Check.NotNull(user, nameof(user));
user.AccessFailedCount++;
return Task.FromResult(user.AccessFailedCount);
}
/// <summary>
/// Resets a user's failed access count.
/// </summary>
/// <param name="user">The user whose failed access count should be reset.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
/// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns>
/// <remarks>This is typically called after the account is successfully accessed.</remarks>
public virtual Task ResetAccessFailedCountAsync([NotNull] TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
Check.NotNull(user, nameof(user));
user.AccessFailedCount = 0;
return Task.CompletedTask;
}
/// <summary>
/// Retrieves the current failed access count for the specified <paramref name="user"/>..
/// </summary>
/// <param name="user">The user whose failed access count should be retrieved.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
/// <returns>The <see cref="Task"/> that represents the asynchronous operation, containing the failed access count.</returns>
public virtual Task<int> GetAccessFailedCountAsync([NotNull] TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
Check.NotNull(user, nameof(user));
return Task.FromResult(user.AccessFailedCount);
}
/// <summary>
/// Retrieves a flag indicating whether user lockout can enabled for the specified user.
/// </summary>
/// <param name="user">The user whose ability to be locked out should be returned.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
/// <returns>
/// The <see cref="Task"/> that represents the asynchronous operation, true if a user can be locked out, otherwise false.
/// </returns>
public virtual Task<bool> GetLockoutEnabledAsync([NotNull] TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
Check.NotNull(user, nameof(user));
return Task.FromResult(user.IsLockoutEnabled);
}
/// <summary>
/// Set the flag indicating if the specified <paramref name="user"/> can be locked out..
/// </summary>
/// <param name="user">The user whose ability to be locked out should be set.</param>
/// <param name="enabled">A flag indicating if lock out can be enabled for the specified <paramref name="user"/>.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
/// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns>
public virtual Task SetLockoutEnabledAsync([NotNull] TUser user, bool enabled, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
Check.NotNull(user, nameof(user));
user.IsLockoutEnabled = enabled;
return Task.CompletedTask;
}
/// <summary>
/// Sets the telephone number for the specified <paramref name="user"/>.
/// </summary>
/// <param name="user">The user whose telephone number should be set.</param>
/// <param name="phoneNumber">The telephone number to set.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
/// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns>
public virtual Task SetPhoneNumberAsync([NotNull] TUser user, string phoneNumber, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
Check.NotNull(user, nameof(user));
user.PhoneNumber = phoneNumber;
return Task.CompletedTask;
}
/// <summary>
/// Gets the telephone number, if any, for the specified <paramref name="user"/>.
/// </summary>
/// <param name="user">The user whose telephone number should be retrieved.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
/// <returns>The <see cref="Task"/> that represents the asynchronous operation, containing the user's telephone number, if any.</returns>
public virtual Task<string> GetPhoneNumberAsync([NotNull] TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
Check.NotNull(user, nameof(user));
return Task.FromResult(user.PhoneNumber);
}
/// <summary>
/// Gets a flag indicating whether the specified <paramref name="user"/>'s telephone number has been confirmed.
/// </summary>
/// <param name="user">The user to return a flag for, indicating whether their telephone number is confirmed.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
/// <returns>
/// The <see cref="Task"/> that represents the asynchronous operation, returning true if the specified <paramref name="user"/> has a confirmed
/// telephone number otherwise false.
/// </returns>
public virtual Task<bool> GetPhoneNumberConfirmedAsync([NotNull] TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
Check.NotNull(user, nameof(user));
return Task.FromResult(user.IsPhoneNumberConfirmed);
}
/// <summary>
/// Sets a flag indicating if the specified <paramref name="user"/>'s phone number has been confirmed..
/// </summary>
/// <param name="user">The user whose telephone number confirmation status should be set.</param>
/// <param name="confirmed">A flag indicating whether the user's telephone number has been confirmed.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
/// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns>
public virtual Task SetPhoneNumberConfirmedAsync([NotNull] TUser user, bool confirmed, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
Check.NotNull(user, nameof(user));
user.IsPhoneNumberConfirmed = confirmed;
return Task.CompletedTask;
}
/// <summary>
/// Sets the provided security <paramref name="stamp"/> for the specified <paramref name="user"/>.
/// </summary>
/// <param name="user">The user whose security stamp should be set.</param>
/// <param name="stamp">The security stamp to set.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
/// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns>
public virtual Task SetSecurityStampAsync([NotNull] TUser user, string stamp, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
Check.NotNull(user, nameof(user));
user.SecurityStamp = stamp;
return Task.CompletedTask;
}
/// <summary>
/// Get the security stamp for the specified <paramref name="user" />.
/// </summary>
/// <param name="user">The user whose security stamp should be set.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
/// <returns>The <see cref="Task"/> that represents the asynchronous operation, containing the security stamp for the specified <paramref name="user"/>.</returns>
public virtual Task<string> GetSecurityStampAsync([NotNull] TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
Check.NotNull(user, nameof(user));
return Task.FromResult(user.SecurityStamp);
}
/// <summary>
/// Sets a flag indicating whether the specified <paramref name="user"/> has two factor authentication enabled or not,
/// as an asynchronous operation.
/// </summary>
/// <param name="user">The user whose two factor authentication enabled status should be set.</param>
/// <param name="enabled">A flag indicating whether the specified <paramref name="user"/> has two factor authentication enabled.</param>