-
Notifications
You must be signed in to change notification settings - Fork 149
/
Copy pathUserManager.cs
1792 lines (1679 loc) · 66.4 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) Microsoft Corporation, Inc. All rights reserved.
// Licensed under the MIT 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.Tasks;
namespace Microsoft.AspNet.Identity
{
/// <summary>
/// UserManager for users where the primary key for the User is of type string
/// </summary>
/// <typeparam name="TUser"></typeparam>
public class UserManager<TUser> : UserManager<TUser, string> where TUser : class, IUser<string>
{
/// <summary>
/// Constructor
/// </summary>
/// <param name="store"></param>
public UserManager(IUserStore<TUser> store)
: base(store)
{
}
}
/// <summary>
/// Exposes user related api which will automatically save changes to the UserStore
/// </summary>
/// <typeparam name="TUser"></typeparam>
/// <typeparam name="TKey"></typeparam>
public class UserManager<TUser, TKey> : IDisposable
where TUser : class, IUser<TKey>
where TKey : IEquatable<TKey>
{
private readonly Dictionary<string, IUserTokenProvider<TUser, TKey>> _factors =
new Dictionary<string, IUserTokenProvider<TUser, TKey>>();
private IClaimsIdentityFactory<TUser, TKey> _claimsFactory;
private TimeSpan _defaultLockout = TimeSpan.Zero;
private bool _disposed;
private IPasswordHasher _passwordHasher;
private IIdentityValidator<string> _passwordValidator;
private IIdentityValidator<TUser> _userValidator;
/// <summary>
/// Constructor
/// </summary>
/// <param name="store">The IUserStore is responsible for commiting changes via the UpdateAsync/CreateAsync methods</param>
public UserManager(IUserStore<TUser, TKey> store)
{
if (store == null)
{
throw new ArgumentNullException("store");
}
Store = store;
UserValidator = new UserValidator<TUser, TKey>(this);
PasswordValidator = new MinimumLengthValidator(6);
PasswordHasher = new PasswordHasher();
ClaimsIdentityFactory = new ClaimsIdentityFactory<TUser, TKey>();
}
/// <summary>
/// Persistence abstraction that the UserManager operates against
/// </summary>
protected internal IUserStore<TUser, TKey> Store { get; set; }
/// <summary>
/// Used to hash/verify passwords
/// </summary>
public IPasswordHasher PasswordHasher
{
get
{
ThrowIfDisposed();
return _passwordHasher;
}
set
{
ThrowIfDisposed();
if (value == null)
{
throw new ArgumentNullException("value");
}
_passwordHasher = value;
}
}
/// <summary>
/// Used to validate users before changes are saved
/// </summary>
public IIdentityValidator<TUser> UserValidator
{
get
{
ThrowIfDisposed();
return _userValidator;
}
set
{
ThrowIfDisposed();
if (value == null)
{
throw new ArgumentNullException("value");
}
_userValidator = value;
}
}
/// <summary>
/// Used to validate passwords before persisting changes
/// </summary>
public IIdentityValidator<string> PasswordValidator
{
get
{
ThrowIfDisposed();
return _passwordValidator;
}
set
{
ThrowIfDisposed();
if (value == null)
{
throw new ArgumentNullException("value");
}
_passwordValidator = value;
}
}
/// <summary>
/// Used to create claims identities from users
/// </summary>
public IClaimsIdentityFactory<TUser, TKey> ClaimsIdentityFactory
{
get
{
ThrowIfDisposed();
return _claimsFactory;
}
set
{
ThrowIfDisposed();
if (value == null)
{
throw new ArgumentNullException("value");
}
_claimsFactory = value;
}
}
/// <summary>
/// Used to send email
/// </summary>
public IIdentityMessageService EmailService { get; set; }
/// <summary>
/// Used to send a sms message
/// </summary>
public IIdentityMessageService SmsService { get; set; }
/// <summary>
/// Used for generating reset password and confirmation tokens
/// </summary>
public IUserTokenProvider<TUser, TKey> UserTokenProvider { get; set; }
/// <summary>
/// If true, will enable user lockout when users are created
/// </summary>
public bool UserLockoutEnabledByDefault { get; set; }
/// <summary>
/// Number of access attempts allowed before a user is locked out (if lockout is enabled)
/// </summary>
public int MaxFailedAccessAttemptsBeforeLockout { get; set; }
/// <summary>
/// Default amount of time that a user is locked out for after MaxFailedAccessAttemptsBeforeLockout is reached
/// </summary>
public TimeSpan DefaultAccountLockoutTimeSpan
{
get { return _defaultLockout; }
set { _defaultLockout = value; }
}
/// <summary>
/// Returns true if the store is an IUserTwoFactorStore
/// </summary>
public virtual bool SupportsUserTwoFactor
{
get
{
ThrowIfDisposed();
return Store is IUserTwoFactorStore<TUser, TKey>;
}
}
/// <summary>
/// Returns true if the store is an IUserPasswordStore
/// </summary>
public virtual bool SupportsUserPassword
{
get
{
ThrowIfDisposed();
return Store is IUserPasswordStore<TUser, TKey>;
}
}
/// <summary>
/// Returns true if the store is an IUserSecurityStore
/// </summary>
public virtual bool SupportsUserSecurityStamp
{
get
{
ThrowIfDisposed();
return Store is IUserSecurityStampStore<TUser, TKey>;
}
}
/// <summary>
/// Returns true if the store is an IUserRoleStore
/// </summary>
public virtual bool SupportsUserRole
{
get
{
ThrowIfDisposed();
return Store is IUserRoleStore<TUser, TKey>;
}
}
/// <summary>
/// Returns true if the store is an IUserLoginStore
/// </summary>
public virtual bool SupportsUserLogin
{
get
{
ThrowIfDisposed();
return Store is IUserLoginStore<TUser, TKey>;
}
}
/// <summary>
/// Returns true if the store is an IUserEmailStore
/// </summary>
public virtual bool SupportsUserEmail
{
get
{
ThrowIfDisposed();
return Store is IUserEmailStore<TUser, TKey>;
}
}
/// <summary>
/// Returns true if the store is an IUserPhoneNumberStore
/// </summary>
public virtual bool SupportsUserPhoneNumber
{
get
{
ThrowIfDisposed();
return Store is IUserPhoneNumberStore<TUser, TKey>;
}
}
/// <summary>
/// Returns true if the store is an IUserClaimStore
/// </summary>
public virtual bool SupportsUserClaim
{
get
{
ThrowIfDisposed();
return Store is IUserClaimStore<TUser, TKey>;
}
}
/// <summary>
/// Returns true if the store is an IUserLockoutStore
/// </summary>
public virtual bool SupportsUserLockout
{
get
{
ThrowIfDisposed();
return Store is IUserLockoutStore<TUser, TKey>;
}
}
/// <summary>
/// Returns true if the store is an IQueryableUserStore
/// </summary>
public virtual bool SupportsQueryableUsers
{
get
{
ThrowIfDisposed();
return Store is IQueryableUserStore<TUser, TKey>;
}
}
/// <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, TKey>;
if (queryableStore == null)
{
throw new NotSupportedException(Resources.StoreNotIQueryableUserStore);
}
return queryableStore.Users;
}
}
/// <summary>
/// Maps the registered two-factor authentication providers for users by their id
/// </summary>
public IDictionary<string, IUserTokenProvider<TUser, TKey>> TwoFactorProviders
{
get { return _factors; }
}
/// <summary>
/// Dispose this object
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Creates a ClaimsIdentity representing the user
/// </summary>
/// <param name="user"></param>
/// <param name="authenticationType"></param>
/// <returns></returns>
public virtual Task<ClaimsIdentity> CreateIdentityAsync(TUser user, string authenticationType)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return ClaimsIdentityFactory.CreateAsync(this, user, authenticationType);
}
/// <summary>
/// Create a user with no password
/// </summary>
/// <param name="user"></param>
/// <returns></returns>
public virtual async Task<IdentityResult> CreateAsync(TUser user)
{
ThrowIfDisposed();
await UpdateSecurityStampInternal(user).WithCurrentCulture();
var result = await UserValidator.ValidateAsync(user).WithCurrentCulture();
if (!result.Succeeded)
{
return result;
}
if (UserLockoutEnabledByDefault && SupportsUserLockout)
{
await GetUserLockoutStore().SetLockoutEnabledAsync(user, true).WithCurrentCulture();
}
await Store.CreateAsync(user).WithCurrentCulture();
return IdentityResult.Success;
}
/// <summary>
/// Update a user
/// </summary>
/// <param name="user"></param>
/// <returns></returns>
public virtual async Task<IdentityResult> UpdateAsync(TUser user)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
var result = await UserValidator.ValidateAsync(user).WithCurrentCulture();
if (!result.Succeeded)
{
return result;
}
await Store.UpdateAsync(user).WithCurrentCulture();
return IdentityResult.Success;
}
/// <summary>
/// Delete a user
/// </summary>
/// <param name="user"></param>
/// <returns></returns>
public virtual async Task<IdentityResult> DeleteAsync(TUser user)
{
ThrowIfDisposed();
await Store.DeleteAsync(user).WithCurrentCulture();
return IdentityResult.Success;
}
/// <summary>
/// Find a user by id
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
public virtual Task<TUser> FindByIdAsync(TKey userId)
{
ThrowIfDisposed();
return Store.FindByIdAsync(userId);
}
/// <summary>
/// Find a user by user name
/// </summary>
/// <param name="userName"></param>
/// <returns></returns>
public virtual Task<TUser> FindByNameAsync(string userName)
{
ThrowIfDisposed();
if (userName == null)
{
throw new ArgumentNullException("userName");
}
return Store.FindByNameAsync(userName);
}
// IUserPasswordStore methods
private IUserPasswordStore<TUser, TKey> GetPasswordStore()
{
var cast = Store as IUserPasswordStore<TUser, TKey>;
if (cast == null)
{
throw new NotSupportedException(Resources.StoreNotIUserPasswordStore);
}
return cast;
}
/// <summary>
/// Create a user with the given password
/// </summary>
/// <param name="user"></param>
/// <param name="password"></param>
/// <returns></returns>
public virtual async Task<IdentityResult> CreateAsync(TUser user, string password)
{
ThrowIfDisposed();
var passwordStore = GetPasswordStore();
if (user == null)
{
throw new ArgumentNullException("user");
}
if (password == null)
{
throw new ArgumentNullException("password");
}
var result = await UpdatePassword(passwordStore, user, password).WithCurrentCulture();
if (!result.Succeeded)
{
return result;
}
return await CreateAsync(user).WithCurrentCulture();
}
/// <summary>
/// Return a user with the specified username and password or null if there is no match.
/// </summary>
/// <param name="userName"></param>
/// <param name="password"></param>
/// <returns></returns>
public virtual async Task<TUser> FindAsync(string userName, string password)
{
ThrowIfDisposed();
var user = await FindByNameAsync(userName).WithCurrentCulture();
if (user == null)
{
return null;
}
return await CheckPasswordAsync(user, password).WithCurrentCulture() ? user : null;
}
/// <summary>
/// Returns true if the password is valid for the user
/// </summary>
/// <param name="user"></param>
/// <param name="password"></param>
/// <returns></returns>
public virtual async Task<bool> CheckPasswordAsync(TUser user, string password)
{
ThrowIfDisposed();
var passwordStore = GetPasswordStore();
if (user == null)
{
return false;
}
return await VerifyPasswordAsync(passwordStore, user, password).WithCurrentCulture();
}
/// <summary>
/// Returns true if the user has a password
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
public virtual async Task<bool> HasPasswordAsync(TKey userId)
{
ThrowIfDisposed();
var passwordStore = GetPasswordStore();
var user = await FindByIdAsync(userId).WithCurrentCulture();
if (user == null)
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, Resources.UserIdNotFound,
userId));
}
return await passwordStore.HasPasswordAsync(user).WithCurrentCulture();
}
/// <summary>
/// Add a user password only if one does not already exist
/// </summary>
/// <param name="userId"></param>
/// <param name="password"></param>
/// <returns></returns>
public virtual async Task<IdentityResult> AddPasswordAsync(TKey userId, string password)
{
ThrowIfDisposed();
var passwordStore = GetPasswordStore();
var user = await FindByIdAsync(userId).WithCurrentCulture();
if (user == null)
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, Resources.UserIdNotFound,
userId));
}
var hash = await passwordStore.GetPasswordHashAsync(user).WithCurrentCulture();
if (hash != null)
{
return new IdentityResult(Resources.UserAlreadyHasPassword);
}
var result = await UpdatePassword(passwordStore, user, password).WithCurrentCulture();
if (!result.Succeeded)
{
return result;
}
return await UpdateAsync(user).WithCurrentCulture();
}
/// <summary>
/// Change a user password
/// </summary>
/// <param name="userId"></param>
/// <param name="currentPassword"></param>
/// <param name="newPassword"></param>
/// <returns></returns>
public virtual async Task<IdentityResult> ChangePasswordAsync(TKey userId, string currentPassword,
string newPassword)
{
ThrowIfDisposed();
var passwordStore = GetPasswordStore();
var user = await FindByIdAsync(userId).WithCurrentCulture();
if (user == null)
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, Resources.UserIdNotFound,
userId));
}
if (await VerifyPasswordAsync(passwordStore, user, currentPassword).WithCurrentCulture())
{
var result = await UpdatePassword(passwordStore, user, newPassword).WithCurrentCulture();
if (!result.Succeeded)
{
return result;
}
return await UpdateAsync(user).WithCurrentCulture();
}
return IdentityResult.Failed(Resources.PasswordMismatch);
}
/// <summary>
/// Remove a user's password
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
public virtual async Task<IdentityResult> RemovePasswordAsync(TKey userId)
{
ThrowIfDisposed();
var passwordStore = GetPasswordStore();
var user = await FindByIdAsync(userId).WithCurrentCulture();
if (user == null)
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, Resources.UserIdNotFound,
userId));
}
await passwordStore.SetPasswordHashAsync(user, null).WithCurrentCulture();
await UpdateSecurityStampInternal(user).WithCurrentCulture();
return await UpdateAsync(user).WithCurrentCulture();
}
protected virtual async Task<IdentityResult> UpdatePassword(IUserPasswordStore<TUser, TKey> passwordStore,
TUser user, string newPassword)
{
var result = await PasswordValidator.ValidateAsync(newPassword).WithCurrentCulture();
if (!result.Succeeded)
{
return result;
}
await
passwordStore.SetPasswordHashAsync(user, PasswordHasher.HashPassword(newPassword)).WithCurrentCulture();
await UpdateSecurityStampInternal(user).WithCurrentCulture();
return IdentityResult.Success;
}
/// <summary>
/// By default, retrieves the hashed password from the user store and calls PasswordHasher.VerifyHashPassword
/// </summary>
/// <param name="store"></param>
/// <param name="user"></param>
/// <param name="password"></param>
/// <returns></returns>
protected virtual async Task<bool> VerifyPasswordAsync(IUserPasswordStore<TUser, TKey> store, TUser user,
string password)
{
var hash = await store.GetPasswordHashAsync(user).WithCurrentCulture();
return PasswordHasher.VerifyHashedPassword(hash, password) != PasswordVerificationResult.Failed;
}
// IUserSecurityStampStore methods
private IUserSecurityStampStore<TUser, TKey> GetSecurityStore()
{
var cast = Store as IUserSecurityStampStore<TUser, TKey>;
if (cast == null)
{
throw new NotSupportedException(Resources.StoreNotIUserSecurityStampStore);
}
return cast;
}
/// <summary>
/// Returns the current security stamp for a user
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
public virtual async Task<string> GetSecurityStampAsync(TKey userId)
{
ThrowIfDisposed();
var securityStore = GetSecurityStore();
var user = await FindByIdAsync(userId).WithCurrentCulture();
if (user == null)
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, Resources.UserIdNotFound,
userId));
}
return await securityStore.GetSecurityStampAsync(user).WithCurrentCulture();
}
/// <summary>
/// Generate a new security stamp for a user, used for SignOutEverywhere functionality
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
public virtual async Task<IdentityResult> UpdateSecurityStampAsync(TKey userId)
{
ThrowIfDisposed();
var securityStore = GetSecurityStore();
var user = await FindByIdAsync(userId).WithCurrentCulture();
if (user == null)
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, Resources.UserIdNotFound,
userId));
}
await securityStore.SetSecurityStampAsync(user, NewSecurityStamp()).WithCurrentCulture();
return await UpdateAsync(user).WithCurrentCulture();
}
/// <summary>
/// Generate a password reset token for the user using the UserTokenProvider
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
public virtual Task<string> GeneratePasswordResetTokenAsync(TKey userId)
{
ThrowIfDisposed();
return GenerateUserTokenAsync("ResetPassword", userId);
}
/// <summary>
/// Reset a user's password using a reset password token
/// </summary>
/// <param name="userId"></param>
/// <param name="token"></param>
/// <param name="newPassword"></param>
/// <returns></returns>
public virtual async Task<IdentityResult> ResetPasswordAsync(TKey userId, string token, string newPassword)
{
ThrowIfDisposed();
var user = await FindByIdAsync(userId).WithCurrentCulture();
if (user == null)
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, Resources.UserIdNotFound,
userId));
}
// Make sure the token is valid and the stamp matches
if (!await VerifyUserTokenAsync(userId, "ResetPassword", token).WithCurrentCulture())
{
return IdentityResult.Failed(Resources.InvalidToken);
}
var passwordStore = GetPasswordStore();
var result = await UpdatePassword(passwordStore, user, newPassword).WithCurrentCulture();
if (!result.Succeeded)
{
return result;
}
return await UpdateAsync(user).WithCurrentCulture();
}
// Update the security stamp if the store supports it
internal async Task UpdateSecurityStampInternal(TUser user)
{
if (SupportsUserSecurityStamp)
{
await GetSecurityStore().SetSecurityStampAsync(user, NewSecurityStamp()).WithCurrentCulture();
}
}
private static string NewSecurityStamp()
{
return Guid.NewGuid().ToString();
}
// IUserLoginStore methods
private IUserLoginStore<TUser, TKey> GetLoginStore()
{
var cast = Store as IUserLoginStore<TUser, TKey>;
if (cast == null)
{
throw new NotSupportedException(Resources.StoreNotIUserLoginStore);
}
return cast;
}
/// <summary>
/// Returns the user associated with this login
/// </summary>
/// <returns></returns>
public virtual Task<TUser> FindAsync(UserLoginInfo login)
{
ThrowIfDisposed();
return GetLoginStore().FindAsync(login);
}
/// <summary>
/// Remove a user login
/// </summary>
/// <param name="userId"></param>
/// <param name="login"></param>
/// <returns></returns>
public virtual async Task<IdentityResult> RemoveLoginAsync(TKey userId, UserLoginInfo login)
{
ThrowIfDisposed();
var loginStore = GetLoginStore();
if (login == null)
{
throw new ArgumentNullException("login");
}
var user = await FindByIdAsync(userId).WithCurrentCulture();
if (user == null)
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, Resources.UserIdNotFound,
userId));
}
await loginStore.RemoveLoginAsync(user, login).WithCurrentCulture();
await UpdateSecurityStampInternal(user).WithCurrentCulture();
return await UpdateAsync(user).WithCurrentCulture();
}
/// <summary>
/// Associate a login with a user
/// </summary>
/// <param name="userId"></param>
/// <param name="login"></param>
/// <returns></returns>
public virtual async Task<IdentityResult> AddLoginAsync(TKey userId, UserLoginInfo login)
{
ThrowIfDisposed();
var loginStore = GetLoginStore();
if (login == null)
{
throw new ArgumentNullException("login");
}
var user = await FindByIdAsync(userId).WithCurrentCulture();
if (user == null)
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, Resources.UserIdNotFound,
userId));
}
var existingUser = await FindAsync(login).WithCurrentCulture();
if (existingUser != null)
{
return IdentityResult.Failed(Resources.ExternalLoginExists);
}
await loginStore.AddLoginAsync(user, login).WithCurrentCulture();
return await UpdateAsync(user).WithCurrentCulture();
}
/// <summary>
/// Gets the logins for a user.
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
public virtual async Task<IList<UserLoginInfo>> GetLoginsAsync(TKey userId)
{
ThrowIfDisposed();
var loginStore = GetLoginStore();
var user = await FindByIdAsync(userId).WithCurrentCulture();
if (user == null)
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, Resources.UserIdNotFound,
userId));
}
return await loginStore.GetLoginsAsync(user).WithCurrentCulture();
}
// IUserClaimStore methods
private IUserClaimStore<TUser, TKey> GetClaimStore()
{
var cast = Store as IUserClaimStore<TUser, TKey>;
if (cast == null)
{
throw new NotSupportedException(Resources.StoreNotIUserClaimStore);
}
return cast;
}
/// <summary>
/// Add a user claim
/// </summary>
/// <param name="userId"></param>
/// <param name="claim"></param>
/// <returns></returns>
public virtual async Task<IdentityResult> AddClaimAsync(TKey userId, Claim claim)
{
ThrowIfDisposed();
var claimStore = GetClaimStore();
if (claim == null)
{
throw new ArgumentNullException("claim");
}
var user = await FindByIdAsync(userId).WithCurrentCulture();
if (user == null)
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, Resources.UserIdNotFound,
userId));
}
await claimStore.AddClaimAsync(user, claim).WithCurrentCulture();
return await UpdateAsync(user).WithCurrentCulture();
}
/// <summary>
/// Remove a user claim
/// </summary>
/// <param name="userId"></param>
/// <param name="claim"></param>
/// <returns></returns>
public virtual async Task<IdentityResult> RemoveClaimAsync(TKey userId, Claim claim)
{
ThrowIfDisposed();
var claimStore = GetClaimStore();
var user = await FindByIdAsync(userId).WithCurrentCulture();
if (user == null)
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, Resources.UserIdNotFound,
userId));
}
await claimStore.RemoveClaimAsync(user, claim).WithCurrentCulture();
return await UpdateAsync(user).WithCurrentCulture();
}
/// <summary>
/// Get a users's claims
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
public virtual async Task<IList<Claim>> GetClaimsAsync(TKey userId)
{
ThrowIfDisposed();
var claimStore = GetClaimStore();
var user = await FindByIdAsync(userId).WithCurrentCulture();
if (user == null)
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, Resources.UserIdNotFound,
userId));
}
return await claimStore.GetClaimsAsync(user).WithCurrentCulture();
}
private IUserRoleStore<TUser, TKey> GetUserRoleStore()
{
var cast = Store as IUserRoleStore<TUser, TKey>;
if (cast == null)
{
throw new NotSupportedException(Resources.StoreNotIUserRoleStore);
}
return cast;
}
/// <summary>
/// Add a user to a role
/// </summary>
/// <param name="userId"></param>
/// <param name="role"></param>
/// <returns></returns>
public virtual async Task<IdentityResult> AddToRoleAsync(TKey userId, string role)
{
ThrowIfDisposed();
var userRoleStore = GetUserRoleStore();
var user = await FindByIdAsync(userId).WithCurrentCulture();
if (user == null)
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, Resources.UserIdNotFound,
userId));
}
var userRoles = await userRoleStore.GetRolesAsync(user).WithCurrentCulture();
if (userRoles.Contains(role))
{
return new IdentityResult(Resources.UserAlreadyInRole);
}
await userRoleStore.AddToRoleAsync(user, role).WithCurrentCulture();
return await UpdateAsync(user).WithCurrentCulture();
}
/// <summary>
/// Method to add user to multiple roles
/// </summary>
/// <param name="userId">user id</param>
/// <param name="roles">list of role names</param>
/// <returns></returns>
public virtual async Task<IdentityResult> AddToRolesAsync(TKey userId, params string[] roles)
{
ThrowIfDisposed();
var userRoleStore = GetUserRoleStore();
if (roles == null)
{
throw new ArgumentNullException("roles");
}
var user = await FindByIdAsync(userId).WithCurrentCulture();
if (user == null)
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, Resources.UserIdNotFound,
userId));
}
var userRoles = await userRoleStore.GetRolesAsync(user).WithCurrentCulture();
foreach (var r in roles)
{
if (userRoles.Contains(r))
{
return new IdentityResult(Resources.UserAlreadyInRole);
}
await userRoleStore.AddToRoleAsync(user, r).WithCurrentCulture();
}
return await UpdateAsync(user).WithCurrentCulture();
}
/// <summary>
/// Remove user from multiple roles
/// </summary>
/// <param name="userId">user id</param>
/// <param name="roles">list of role names</param>
/// <returns></returns>
public virtual async Task<IdentityResult> RemoveFromRolesAsync(TKey userId, params string[] roles)
{
ThrowIfDisposed();
var userRoleStore = GetUserRoleStore();
if (roles == null)
{
throw new ArgumentNullException("roles");
}
var user = await FindByIdAsync(userId).WithCurrentCulture();
if (user == null)
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, Resources.UserIdNotFound,
userId));
}
// Remove user to each role using UserRoleStore
var userRoles = await userRoleStore.GetRolesAsync(user).WithCurrentCulture();
foreach (var role in roles)
{
if (!userRoles.Contains(role))
{
return new IdentityResult(Resources.UserNotInRole);
}