This repository has been archived by the owner on Dec 20, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 866
/
UserManager.cs
2319 lines (2144 loc) · 97.2 KB
/
UserManager.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
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace Microsoft.AspNetCore.Identity
{
/// <summary>
/// Provides the APIs for managing user in a persistence store.
/// </summary>
/// <typeparam name="TUser">The type encapsulating a user.</typeparam>
public class UserManager<TUser> : IDisposable where TUser : class
{
/// <summary>
/// The data protection purpose used for the reset password related methods.
/// </summary>
protected const string ResetPasswordTokenPurpose = "ResetPassword";
/// <summary>
/// The data protection purpose used for the email confirmation related methods.
/// </summary>
protected const string ConfirmEmailTokenPurpose = "EmailConfirmation";
private readonly Dictionary<string, IUserTwoFactorTokenProvider<TUser>> _tokenProviders =
new Dictionary<string, IUserTwoFactorTokenProvider<TUser>>();
private TimeSpan _defaultLockout = TimeSpan.Zero;
private bool _disposed;
private readonly HttpContext _context;
/// <summary>
/// The cancellation token assocated with the current HttpContext.RequestAborted or CancellationToken.None if unavailable.
/// </summary>
protected CancellationToken CancellationToken => _context?.RequestAborted ?? CancellationToken.None;
/// <summary>
/// Constructs a new instance of <see cref="UserManager{TUser}"/>.
/// </summary>
/// <param name="store">The persistence store the manager will operate over.</param>
/// <param name="optionsAccessor">The accessor used to access the <see cref="IdentityOptions"/>.</param>
/// <param name="passwordHasher">The password hashing implementation to use when saving passwords.</param>
/// <param name="userValidators">A collection of <see cref="IUserValidator{TUser}"/> to validate users against.</param>
/// <param name="passwordValidators">A collection of <see cref="IPasswordValidator{TUser}"/> to validate passwords against.</param>
/// <param name="keyNormalizer">The <see cref="ILookupNormalizer"/> to use when generating index keys for users.</param>
/// <param name="errors">The <see cref="IdentityErrorDescriber"/> used to provider error messages.</param>
/// <param name="services">The <see cref="IServiceProvider"/> used to resolve services.</param>
/// <param name="logger">The logger used to log messages, warnings and errors.</param>
public UserManager(IUserStore<TUser> store,
IOptions<IdentityOptions> optionsAccessor,
IPasswordHasher<TUser> passwordHasher,
IEnumerable<IUserValidator<TUser>> userValidators,
IEnumerable<IPasswordValidator<TUser>> passwordValidators,
ILookupNormalizer keyNormalizer,
IdentityErrorDescriber errors,
IServiceProvider services,
ILogger<UserManager<TUser>> logger)
{
if (store == null)
{
throw new ArgumentNullException(nameof(store));
}
Store = store;
Options = optionsAccessor?.Value ?? new IdentityOptions();
PasswordHasher = passwordHasher;
KeyNormalizer = keyNormalizer;
ErrorDescriber = errors;
Logger = logger;
if (userValidators != null)
{
foreach (var v in userValidators)
{
UserValidators.Add(v);
}
}
if (passwordValidators != null)
{
foreach (var v in passwordValidators)
{
PasswordValidators.Add(v);
}
}
if (services != null)
{
_context = services.GetService<IHttpContextAccessor>()?.HttpContext;
foreach (var providerName in Options.Tokens.ProviderMap.Keys)
{
var description = Options.Tokens.ProviderMap[providerName];
var provider = (description.ProviderInstance ?? services.GetRequiredService(description.ProviderType))
as IUserTwoFactorTokenProvider<TUser>;
if (provider != null)
{
RegisterTokenProvider(providerName, provider);
}
}
}
}
/// <summary>
/// Gets or sets the persistence store the manager operates over.
/// </summary>
/// <value>The persistence store the manager operates over.</value>
protected internal IUserStore<TUser> Store { get; set; }
/// <summary>
/// The <see cref="ILogger"/> used to log messages from the manager.
/// </summary>
/// <value>
/// The <see cref="ILogger"/> used to log messages from the manager.
/// </value>
protected internal virtual ILogger Logger { get; set; }
/// <summary>
/// The <see cref="IPasswordHasher{TUser}"/> used to hash passwords.
/// </summary>
protected internal IPasswordHasher<TUser> PasswordHasher { get; set; }
/// <summary>
/// The <see cref="IUserValidator{TUser}"/> used to validate users.
/// </summary>
protected internal IList<IUserValidator<TUser>> UserValidators { get; } = new List<IUserValidator<TUser>>();
/// <summary>
/// The <see cref="IPasswordValidator{TUser}"/> used to validate passwords.
/// </summary>
protected internal IList<IPasswordValidator<TUser>> PasswordValidators { get; } = new List<IPasswordValidator<TUser>>();
/// <summary>
/// The <see cref="ILookupNormalizer"/> used to normalize things like user and role names.
/// </summary>
protected internal ILookupNormalizer KeyNormalizer { get; set; }
/// <summary>
/// The <see cref="IdentityErrorDescriber"/> used to generate error messages.
/// </summary>
protected internal IdentityErrorDescriber ErrorDescriber { get; set; }
/// <summary>
/// The <see cref="IdentityOptions"/> used to configure Identity.
/// </summary>
protected internal IdentityOptions Options { get; set; }
/// <summary>
/// Gets a flag indicating whether the backing user store supports authentication tokens.
/// </summary>
/// <value>
/// true if the backing user store supports authentication tokens, otherwise false.
/// </value>
public virtual bool SupportsUserAuthenticationTokens
{
get
{
ThrowIfDisposed();
return Store is IUserAuthenticationTokenStore<TUser>;
}
}
/// <summary>
/// Gets a flag indicating whether the backing user store supports two factor authentication.
/// </summary>
/// <value>
/// true if the backing user store supports user two factor authentication, otherwise false.
/// </value>
public virtual bool SupportsUserTwoFactor
{
get
{
ThrowIfDisposed();
return Store is IUserTwoFactorStore<TUser>;
}
}
/// <summary>
/// Gets a flag indicating whether the backing user store supports user passwords.
/// </summary>
/// <value>
/// true if the backing user store supports user passwords, otherwise false.
/// </value>
public virtual bool SupportsUserPassword
{
get
{
ThrowIfDisposed();
return Store is IUserPasswordStore<TUser>;
}
}
/// <summary>
/// Gets a flag indicating whether the backing user store supports security stamps.
/// </summary>
/// <value>
/// true if the backing user store supports user security stamps, otherwise false.
/// </value>
public virtual bool SupportsUserSecurityStamp
{
get
{
ThrowIfDisposed();
return Store is IUserSecurityStampStore<TUser>;
}
}
/// <summary>
/// Gets a flag indicating whether the backing user store supports user roles.
/// </summary>
/// <value>
/// true if the backing user store supports user roles, otherwise false.
/// </value>
public virtual bool SupportsUserRole
{
get
{
ThrowIfDisposed();
return Store is IUserRoleStore<TUser>;
}
}
/// <summary>
/// Gets a flag indicating whether the backing user store supports external logins.
/// </summary>
/// <value>
/// true if the backing user store supports external logins, otherwise false.
/// </value>
public virtual bool SupportsUserLogin
{
get
{
ThrowIfDisposed();
return Store is IUserLoginStore<TUser>;
}
}
/// <summary>
/// Gets a flag indicating whether the backing user store supports user emails.
/// </summary>
/// <value>
/// true if the backing user store supports user emails, otherwise false.
/// </value>
public virtual bool SupportsUserEmail
{
get
{
ThrowIfDisposed();
return Store is IUserEmailStore<TUser>;
}
}
/// <summary>
/// Gets a flag indicating whether the backing user store supports user telephone numbers.
/// </summary>
/// <value>
/// true if the backing user store supports user telephone numbers, otherwise false.
/// </value>
public virtual bool SupportsUserPhoneNumber
{
get
{
ThrowIfDisposed();
return Store is IUserPhoneNumberStore<TUser>;
}
}
/// <summary>
/// Gets a flag indicating whether the backing user store supports user claims.
/// </summary>
/// <value>
/// true if the backing user store supports user claims, otherwise false.
/// </value>
public virtual bool SupportsUserClaim
{
get
{
ThrowIfDisposed();
return Store is IUserClaimStore<TUser>;
}
}
/// <summary>
/// Gets a flag indicating whether the backing user store supports user lock-outs.
/// </summary>
/// <value>
/// true if the backing user store supports user lock-outs, otherwise false.
/// </value>
public virtual bool SupportsUserLockout
{
get
{
ThrowIfDisposed();
return Store is IUserLockoutStore<TUser>;
}
}
/// <summary>
/// Gets a flag indicating whether the backing user store supports returning
/// <see cref="IQueryable"/> collections of information.
/// </summary>
/// <value>
/// true if the backing user store supports returning <see cref="IQueryable"/> collections of
/// information, otherwise false.
/// </value>
public virtual bool SupportsQueryableUsers
{
get
{
ThrowIfDisposed();
return Store is IQueryableUserStore<TUser>;
}
}
/// <summary>
/// Returns an IQueryable of users if the store is an IQueryableUserStore
/// </summary>
public virtual IQueryable<TUser> Users
{
get
{
var queryableStore = Store as IQueryableUserStore<TUser>;
if (queryableStore == null)
{
throw new NotSupportedException(Resources.StoreNotIQueryableUserStore);
}
return queryableStore.Users;
}
}
/// <summary>
/// Releases all resources used by the user manager.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Returns the Name claim value if present otherwise returns null.
/// </summary>
/// <param name="principal">The <see cref="ClaimsPrincipal"/> instance.</param>
/// <returns>The Name claim value, or null if the claim is not present.</returns>
/// <remarks>The Name claim is identified by <see cref="ClaimsIdentity.DefaultNameClaimType"/>.</remarks>
public virtual string GetUserName(ClaimsPrincipal principal)
{
if (principal == null)
{
throw new ArgumentNullException(nameof(principal));
}
return principal.FindFirstValue(Options.ClaimsIdentity.UserNameClaimType);
}
/// <summary>
/// Returns the User ID claim value if present otherwise returns null.
/// </summary>
/// <param name="principal">The <see cref="ClaimsPrincipal"/> instance.</param>
/// <returns>The User ID claim value, or null if the claim is not present.</returns>
/// <remarks>The User ID claim is identified by <see cref="ClaimTypes.NameIdentifier"/>.</remarks>
public virtual string GetUserId(ClaimsPrincipal principal)
{
if (principal == null)
{
throw new ArgumentNullException(nameof(principal));
}
return principal.FindFirstValue(Options.ClaimsIdentity.UserIdClaimType);
}
/// <summary>
/// Returns the user corresponding to the IdentityOptions.ClaimsIdentity.UserIdClaimType claim in
/// the principal or null.
/// </summary>
/// <param name="principal">The principal which contains the user id claim.</param>
/// <returns>The user corresponding to the IdentityOptions.ClaimsIdentity.UserIdClaimType claim in
/// the principal or null</returns>
public virtual Task<TUser> GetUserAsync(ClaimsPrincipal principal)
{
if (principal == null)
{
throw new ArgumentNullException(nameof(principal));
}
var id = GetUserId(principal);
return id == null ? Task.FromResult<TUser>(null) : FindByIdAsync(id);
}
/// <summary>
/// Generates a value suitable for use in concurrency tracking.
/// </summary>
/// <param name="user">The user to generate the stamp for.</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> GenerateConcurrencyStampAsync(TUser user)
{
return Task.FromResult(Guid.NewGuid().ToString());
}
/// <summary>
/// Creates the specified <paramref name="user"/> in the backing store with no password,
/// as an asynchronous operation.
/// </summary>
/// <param name="user">The user to create.</param>
/// <returns>
/// The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/>
/// of the operation.
/// </returns>
public virtual async Task<IdentityResult> CreateAsync(TUser user)
{
ThrowIfDisposed();
await UpdateSecurityStampInternal(user);
var result = await ValidateUserInternal(user);
if (!result.Succeeded)
{
return result;
}
if (Options.Lockout.AllowedForNewUsers && SupportsUserLockout)
{
await GetUserLockoutStore().SetLockoutEnabledAsync(user, true, CancellationToken);
}
await UpdateNormalizedUserNameAsync(user);
await UpdateNormalizedEmailAsync(user);
return await Store.CreateAsync(user, CancellationToken);
}
/// <summary>
/// Updates the specified <paramref name="user"/> in the backing store.
/// </summary>
/// <param name="user">The user to update.</param>
/// <returns>
/// The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/>
/// of the operation.
/// </returns>
public virtual Task<IdentityResult> UpdateAsync(TUser user)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
return UpdateUserAsync(user);
}
/// <summary>
/// Deletes the specified <paramref name="user"/> from the backing store.
/// </summary>
/// <param name="user">The user to delete.</param>
/// <returns>
/// The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/>
/// of the operation.
/// </returns>
public virtual Task<IdentityResult> DeleteAsync(TUser user)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
return Store.DeleteAsync(user, CancellationToken);
}
/// <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>
/// <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)
{
ThrowIfDisposed();
return Store.FindByIdAsync(userId, CancellationToken);
}
/// <summary>
/// Finds and returns a user, if any, who has the specified user name.
/// </summary>
/// <param name="userName">The user name to search for.</param>
/// <returns>
/// The <see cref="Task"/> that represents the asynchronous operation, containing the user matching the specified <paramref name="userName"/> if it exists.
/// </returns>
public virtual Task<TUser> FindByNameAsync(string userName)
{
ThrowIfDisposed();
if (userName == null)
{
throw new ArgumentNullException(nameof(userName));
}
userName = NormalizeKey(userName);
return Store.FindByNameAsync(userName, CancellationToken);
}
/// <summary>
/// Creates the specified <paramref name="user"/> in the backing store with given password,
/// as an asynchronous operation.
/// </summary>
/// <param name="user">The user to create.</param>
/// <param name="password">The password for the user to hash and store.</param>
/// <returns>
/// The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/>
/// of the operation.
/// </returns>
public virtual async Task<IdentityResult> CreateAsync(TUser user, string password)
{
ThrowIfDisposed();
var passwordStore = GetPasswordStore();
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
if (password == null)
{
throw new ArgumentNullException(nameof(password));
}
var result = await UpdatePasswordHash(passwordStore, user, password);
if (!result.Succeeded)
{
return result;
}
return await CreateAsync(user);
}
/// <summary>
/// Normalize a key (user name, email) for consistent comparisons.
/// </summary>
/// <param name="key">The key to normalize.</param>
/// <returns>A normalized value representing the specified <paramref name="key"/>.</returns>
public virtual string NormalizeKey(string key)
{
return (KeyNormalizer == null) ? key : KeyNormalizer.Normalize(key);
}
/// <summary>
/// Updates the normalized user name for the specified <paramref name="user"/>.
/// </summary>
/// <param name="user">The user whose user name should be normalized and updated.</param>
/// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns>
public virtual async Task UpdateNormalizedUserNameAsync(TUser user)
{
var normalizedName = NormalizeKey(await GetUserNameAsync(user));
await Store.SetNormalizedUserNameAsync(user, normalizedName, CancellationToken);
}
/// <summary>
/// Gets the user name for the specified <paramref name="user"/>.
/// </summary>
/// <param name="user">The user whose name should be retrieved.</param>
/// <returns>The <see cref="Task"/> that represents the asynchronous operation, containing the name for the specified <paramref name="user"/>.</returns>
public virtual async Task<string> GetUserNameAsync(TUser user)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
return await Store.GetUserNameAsync(user, CancellationToken);
}
/// <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>
/// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns>
public virtual async Task<IdentityResult> SetUserNameAsync(TUser user, string userName)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
await Store.SetUserNameAsync(user, userName, CancellationToken);
await UpdateSecurityStampInternal(user);
return await UpdateUserAsync(user);
}
/// <summary>
/// Gets the user identifier for the specified <paramref name="user"/>.
/// </summary>
/// <param name="user">The user whose identifier should be retrieved.</param>
/// <returns>The <see cref="Task"/> that represents the asynchronous operation, containing the identifier for the specified <paramref name="user"/>.</returns>
public virtual async Task<string> GetUserIdAsync(TUser user)
{
ThrowIfDisposed();
return await Store.GetUserIdAsync(user, CancellationToken);
}
/// <summary>
/// Returns a flag indicating whether the given <paramref name="password"/> is valid for the
/// specified <paramref name="user"/>.
/// </summary>
/// <param name="user">The user whose password should be validated.</param>
/// <param name="password">The password to validate</param>
/// <returns>The <see cref="Task"/> that represents the asynchronous operation, containing true if
/// the specified <paramref name="password" /> matches the one store for the <paramref name="user"/>,
/// otherwise false.</returns>
public virtual async Task<bool> CheckPasswordAsync(TUser user, string password)
{
ThrowIfDisposed();
var passwordStore = GetPasswordStore();
if (user == null)
{
return false;
}
var result = await VerifyPasswordAsync(passwordStore, user, password);
if (result == PasswordVerificationResult.SuccessRehashNeeded)
{
await UpdatePasswordHash(passwordStore, user, password, validatePassword: false);
await UpdateUserAsync(user);
}
var success = result != PasswordVerificationResult.Failed;
if (!success)
{
Logger.LogWarning(0, "Invalid password for user {userId}.", await GetUserIdAsync(user));
}
return success;
}
/// <summary>
/// Gets a flag indicating whether the specified <paramref name="user"/> has a password.
/// </summary>
/// <param name="user">The user to return a flag for, indicating whether they have a password or not.</param>
/// <returns>
/// The <see cref="Task"/> that represents the asynchronous operation, returning true if the specified <paramref name="user"/> has a password
/// otherwise false.
/// </returns>
public virtual Task<bool> HasPasswordAsync(TUser user)
{
ThrowIfDisposed();
var passwordStore = GetPasswordStore();
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
return passwordStore.HasPasswordAsync(user, CancellationToken);
}
/// <summary>
/// Adds the <paramref name="password"/> to the specified <paramref name="user"/> only if the user
/// does not already have a password.
/// </summary>
/// <param name="user">The user whose password should be set.</param>
/// <param name="password">The password to set.</param>
/// <returns>
/// The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/>
/// of the operation.
/// </returns>
public virtual async Task<IdentityResult> AddPasswordAsync(TUser user, string password)
{
ThrowIfDisposed();
var passwordStore = GetPasswordStore();
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
var hash = await passwordStore.GetPasswordHashAsync(user, CancellationToken);
if (hash != null)
{
Logger.LogWarning(1, "User {userId} already has a password.", await GetUserIdAsync(user));
return IdentityResult.Failed(ErrorDescriber.UserAlreadyHasPassword());
}
var result = await UpdatePasswordHash(passwordStore, user, password);
if (!result.Succeeded)
{
return result;
}
return await UpdateUserAsync(user);
}
/// <summary>
/// Changes a user's password after confirming the specified <paramref name="currentPassword"/> is correct,
/// as an asynchronous operation.
/// </summary>
/// <param name="user">The user whose password should be set.</param>
/// <param name="currentPassword">The current password to validate before changing.</param>
/// <param name="newPassword">The new password to set for the specified <paramref name="user"/>.</param>
/// <returns>
/// The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/>
/// of the operation.
/// </returns>
public virtual async Task<IdentityResult> ChangePasswordAsync(TUser user, string currentPassword, string newPassword)
{
ThrowIfDisposed();
var passwordStore = GetPasswordStore();
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
if (await VerifyPasswordAsync(passwordStore, user, currentPassword) != PasswordVerificationResult.Failed)
{
var result = await UpdatePasswordHash(passwordStore, user, newPassword);
if (!result.Succeeded)
{
return result;
}
return await UpdateUserAsync(user);
}
Logger.LogWarning(2, "Change password failed for user {userId}.", await GetUserIdAsync(user));
return IdentityResult.Failed(ErrorDescriber.PasswordMismatch());
}
/// <summary>
/// Removes a user's password.
/// </summary>
/// <param name="user">The user whose password should be removed.</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 operation.
/// </returns>
public virtual async Task<IdentityResult> RemovePasswordAsync(TUser user,
CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
var passwordStore = GetPasswordStore();
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
await UpdatePasswordHash(passwordStore, user, null, validatePassword: false);
return await UpdateUserAsync(user);
}
/// <summary>
/// Returns a <see cref="PasswordVerificationResult"/> indicating the result of a password hash comparison.
/// </summary>
/// <param name="store">The store containing a user's password.</param>
/// <param name="user">The user whose password should be verified.</param>
/// <param name="password">The password to verify.</param>
/// <returns>
/// The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="PasswordVerificationResult"/>
/// of the operation.
/// </returns>
protected virtual async Task<PasswordVerificationResult> VerifyPasswordAsync(IUserPasswordStore<TUser> store, TUser user, string password)
{
var hash = await store.GetPasswordHashAsync(user, CancellationToken);
if (hash == null)
{
return PasswordVerificationResult.Failed;
}
return PasswordHasher.VerifyHashedPassword(user, hash, password);
}
/// <summary>
/// Get the security stamp for the specified <paramref name="user" />.
/// </summary>
/// <param name="user">The user whose security stamp should be set.</param>
/// <returns>The <see cref="Task"/> that represents the asynchronous operation, containing the security stamp for the specified <paramref name="user"/>.</returns>
public virtual async Task<string> GetSecurityStampAsync(TUser user)
{
ThrowIfDisposed();
var securityStore = GetSecurityStore();
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
return await securityStore.GetSecurityStampAsync(user, CancellationToken);
}
/// <summary>
/// Regenerates the security stamp for the specified <paramref name="user" />.
/// </summary>
/// <param name="user">The user whose security stamp should be regenerated.</param>
/// <returns>
/// The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/>
/// of the operation.
/// </returns>
/// <remarks>
/// Regenerating a security stamp will sign out any saved login for the user.
/// </remarks>
public virtual async Task<IdentityResult> UpdateSecurityStampAsync(TUser user)
{
ThrowIfDisposed();
GetSecurityStore();
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
await UpdateSecurityStampInternal(user);
return await UpdateUserAsync(user);
}
/// <summary>
/// Generates a password reset token for the specified <paramref name="user"/>, using
/// the configured password reset token provider.
/// </summary>
/// <param name="user">The user to generate a password reset token for.</param>
/// <returns>The <see cref="Task"/> that represents the asynchronous operation,
/// containing a password reset token for the specified <paramref name="user"/>.</returns>
public virtual Task<string> GeneratePasswordResetTokenAsync(TUser user)
{
ThrowIfDisposed();
return GenerateUserTokenAsync(user, Options.Tokens.PasswordResetTokenProvider, ResetPasswordTokenPurpose);
}
/// <summary>
/// Resets the <paramref name="user"/>'s password to the specified <paramref name="newPassword"/> after
/// validating the given password reset <paramref name="token"/>.
/// </summary>
/// <param name="user">The user whose password should be reset.</param>
/// <param name="token">The password reset token to verify.</param>
/// <param name="newPassword">The new password to set if reset token verification fails.</param>
/// <returns>
/// The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/>
/// of the operation.
/// </returns>
public virtual async Task<IdentityResult> ResetPasswordAsync(TUser user, string token, string newPassword)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
// Make sure the token is valid and the stamp matches
if (!await VerifyUserTokenAsync(user, Options.Tokens.PasswordResetTokenProvider, ResetPasswordTokenPurpose, token))
{
return IdentityResult.Failed(ErrorDescriber.InvalidToken());
}
var passwordStore = GetPasswordStore();
var result = await UpdatePasswordHash(passwordStore, user, newPassword);
if (!result.Succeeded)
{
return result;
}
return await UpdateUserAsync(user);
}
/// <summary>
/// Retrieves the user associated with the specified external 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>
/// <returns>
/// The <see cref="Task"/> for the asynchronous operation, containing the user, if any which matched the specified login provider and key.
/// </returns>
public virtual Task<TUser> FindByLoginAsync(string loginProvider, string providerKey)
{
ThrowIfDisposed();
var loginStore = GetLoginStore();
if (loginProvider == null)
{
throw new ArgumentNullException(nameof(loginProvider));
}
if (providerKey == null)
{
throw new ArgumentNullException(nameof(providerKey));
}
return loginStore.FindByLoginAsync(loginProvider, providerKey, CancellationToken);
}
/// <summary>
/// Attempts to remove the provided external login information from the specified <paramref name="user"/>.
/// and returns a flag indicating whether the removal succeed or not.
/// </summary>
/// <param name="user">The user to remove the login information from.</param>
/// <param name="loginProvider">The login provide whose information should be removed.</param>
/// <param name="providerKey">The key given by the external login provider for the specified user.</param>
/// <returns>
/// The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/>
/// of the operation.
/// </returns>
public virtual async Task<IdentityResult> RemoveLoginAsync(TUser user, string loginProvider, string providerKey)
{
ThrowIfDisposed();
var loginStore = GetLoginStore();
if (loginProvider == null)
{
throw new ArgumentNullException(nameof(loginProvider));
}
if (providerKey == null)
{
throw new ArgumentNullException(nameof(providerKey));
}
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
await loginStore.RemoveLoginAsync(user, loginProvider, providerKey, CancellationToken);
await UpdateSecurityStampInternal(user);
return await UpdateUserAsync(user);
}
/// <summary>
/// Adds an external <see cref="UserLoginInfo"/> to the specified <paramref name="user"/>.
/// </summary>
/// <param name="user">The user to add the login to.</param>
/// <param name="login">The external <see cref="UserLoginInfo"/> to add to the specified <paramref name="user"/>.</param>
/// <returns>
/// The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/>
/// of the operation.
/// </returns>
public virtual async Task<IdentityResult> AddLoginAsync(TUser user, UserLoginInfo login)
{
ThrowIfDisposed();
var loginStore = GetLoginStore();
if (login == null)
{
throw new ArgumentNullException(nameof(login));
}
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
var existingUser = await FindByLoginAsync(login.LoginProvider, login.ProviderKey);
if (existingUser != null)
{
Logger.LogWarning(4, "AddLogin for user {userId} failed because it was already assocated with another user.", await GetUserIdAsync(user));
return IdentityResult.Failed(ErrorDescriber.LoginAlreadyAssociated());
}
await loginStore.AddLoginAsync(user, login, CancellationToken);
return await UpdateUserAsync(user);
}
/// <summary>
/// Retrieves the associated logins for the specified <param ref="user"/>.
/// </summary>
/// <param name="user">The user whose associated logins to retrieve.</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(TUser user)
{
ThrowIfDisposed();
var loginStore = GetLoginStore();
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
return await loginStore.GetLoginsAsync(user, CancellationToken);
}
/// <summary>
/// Adds the specified <paramref name="claim"/> to the <paramref name="user"/>.
/// </summary>
/// <param name="user">The user to add the claim to.</param>
/// <param name="claim">The claim to add.</param>
/// <returns>
/// The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/>
/// of the operation.
/// </returns>
public virtual Task<IdentityResult> AddClaimAsync(TUser user, Claim claim)
{
ThrowIfDisposed();
var claimStore = GetClaimStore();
if (claim == null)
{
throw new ArgumentNullException(nameof(claim));
}
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
return AddClaimsAsync(user, new Claim[] { claim });
}
/// <summary>
/// Adds the specified <paramref name="claims"/> to the <paramref name="user"/>.
/// </summary>
/// <param name="user">The user to add the claim to.</param>
/// <param name="claims">The claims to add.</param>
/// <returns>
/// The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/>
/// of the operation.
/// </returns>
public virtual async Task<IdentityResult> AddClaimsAsync(TUser user, IEnumerable<Claim> claims)
{
ThrowIfDisposed();
var claimStore = GetClaimStore();
if (claims == null)
{
throw new ArgumentNullException(nameof(claims));
}
if (user == null)
{
throw new ArgumentNullException(nameof(user));