// Copyright (c) Microsoft Open Technologies, Inc. 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.AspNet.Hosting; using Microsoft.AspNet.Http; using Microsoft.Framework.Logging; using Microsoft.Framework.OptionsModel; namespace Microsoft.AspNet.Identity { /// /// Exposes user related api which will automatically save changes to the UserStore /// /// public class UserManager : IDisposable where TUser : class { private readonly Dictionary> _tokenProviders = new Dictionary>(); private TimeSpan _defaultLockout = TimeSpan.Zero; private bool _disposed; private HttpContext _context; /// /// Constructor /// /// /// /// /// /// /// /// /// /// public UserManager(IUserStore store, IOptions optionsAccessor, IPasswordHasher passwordHasher, IEnumerable> userValidators, IEnumerable> passwordValidators, ILookupNormalizer keyNormalizer, IdentityErrorDescriber errors, IEnumerable> tokenProviders, ILoggerFactory logger, IHttpContextAccessor contextAccessor) { if (store == null) { throw new ArgumentNullException(nameof(store)); } Store = store; Options = optionsAccessor?.Options ?? new IdentityOptions(); _context = contextAccessor?.HttpContext; PasswordHasher = passwordHasher; KeyNormalizer = keyNormalizer; ErrorDescriber = errors; if (userValidators != null) { foreach (var v in userValidators) { UserValidators.Add(v); } } if (passwordValidators != null) { foreach (var v in passwordValidators) { PasswordValidators.Add(v); } } Logger = logger?.CreateLogger>() ?? new Logger>(new LoggerFactory()); if (tokenProviders != null) { foreach (var tokenProvider in tokenProviders) { RegisterTokenProvider(tokenProvider); } } } /// /// Persistence abstraction that the Manager operates against /// protected internal IUserStore Store { get; set; } internal IPasswordHasher PasswordHasher { get; set; } internal IList> UserValidators { get; } = new List>(); internal IList> PasswordValidators { get; } = new List>(); internal ILookupNormalizer KeyNormalizer { get; set; } internal IdentityErrorDescriber ErrorDescriber { get; set; } internal ILogger Logger { get; set; } internal IdentityOptions Options { get; set; } /// /// Returns true if the store is an IUserTwoFactorStore /// public virtual bool SupportsUserTwoFactor { get { ThrowIfDisposed(); return Store is IUserTwoFactorStore; } } /// /// Returns true if the store is an IUserPasswordStore /// public virtual bool SupportsUserPassword { get { ThrowIfDisposed(); return Store is IUserPasswordStore; } } /// /// Returns true if the store is an IUserSecurityStore /// public virtual bool SupportsUserSecurityStamp { get { ThrowIfDisposed(); return Store is IUserSecurityStampStore; } } /// /// Returns true if the store is an IUserRoleStore /// public virtual bool SupportsUserRole { get { ThrowIfDisposed(); return Store is IUserRoleStore; } } /// /// Returns true if the store is an IUserLoginStore /// public virtual bool SupportsUserLogin { get { ThrowIfDisposed(); return Store is IUserLoginStore; } } /// /// Returns true if the store is an IUserEmailStore /// public virtual bool SupportsUserEmail { get { ThrowIfDisposed(); return Store is IUserEmailStore; } } /// /// Returns true if the store is an IUserPhoneNumberStore /// public virtual bool SupportsUserPhoneNumber { get { ThrowIfDisposed(); return Store is IUserPhoneNumberStore; } } /// /// Returns true if the store is an IUserClaimStore /// public virtual bool SupportsUserClaim { get { ThrowIfDisposed(); return Store is IUserClaimStore; } } /// /// Returns true if the store is an IUserLockoutStore /// public virtual bool SupportsUserLockout { get { ThrowIfDisposed(); return Store is IUserLockoutStore; } } /// /// Returns true if the store is an IQueryableUserStore /// public virtual bool SupportsQueryableUsers { get { ThrowIfDisposed(); return Store is IQueryableUserStore; } } /// /// Returns an IQueryable of users if the store is an IQueryableUserStore /// public virtual IQueryable Users { get { var queryableStore = Store as IQueryableUserStore; if (queryableStore == null) { throw new NotSupportedException(Resources.StoreNotIQueryableUserStore); } return queryableStore.Users; } } private CancellationToken CancellationToken { get { return _context?.RequestAborted ?? CancellationToken.None; } } /// /// Dispose the store context /// public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private async Task ValidateUserInternal(TUser user) { var errors = new List(); foreach (var v in UserValidators) { var result = await v.ValidateAsync(this, user); if (!result.Succeeded) { errors.AddRange(result.Errors); } } return errors.Count > 0 ? IdentityResult.Failed(errors.ToArray()) : IdentityResult.Success; } private async Task ValidatePasswordInternal(TUser user, string password) { var errors = new List(); foreach (var v in PasswordValidators) { var result = await v.ValidateAsync(this, user, password); if (!result.Succeeded) { errors.AddRange(result.Errors); } } return errors.Count > 0 ? IdentityResult.Failed(errors.ToArray()) : IdentityResult.Success; } public virtual Task GenerateConcurrencyStampAsync(TUser user) { return Task.FromResult(Guid.NewGuid().ToString()); } /// /// Validate user and update. Called by other UserManager methods /// /// /// private async Task UpdateUserAsync(TUser user) { var result = await ValidateUserInternal(user); if (!result.Succeeded) { return result; } await UpdateNormalizedUserNameAsync(user); await UpdateNormalizedEmailAsync(user); return await Store.UpdateAsync(user, CancellationToken); } /// /// Create a user with no password /// /// /// public virtual async Task CreateAsync(TUser user) { ThrowIfDisposed(); await UpdateSecurityStampInternal(user); var result = await ValidateUserInternal(user); if (!result.Succeeded) { return result; } if (Options.Lockout.EnabledByDefault && SupportsUserLockout) { await GetUserLockoutStore().SetLockoutEnabledAsync(user, true, CancellationToken); } await UpdateNormalizedUserNameAsync(user); await UpdateNormalizedEmailAsync(user); return await LogResultAsync(await Store.CreateAsync(user, CancellationToken), user); } /// /// Update a user /// /// /// public virtual async Task UpdateAsync(TUser user) { ThrowIfDisposed(); if (user == null) { throw new ArgumentNullException("user"); } return await LogResultAsync(await UpdateUserAsync(user), user); } /// /// Delete a user /// /// /// public virtual async Task DeleteAsync(TUser user) { ThrowIfDisposed(); if (user == null) { throw new ArgumentNullException("user"); } return await LogResultAsync(await Store.DeleteAsync(user, CancellationToken), user); } /// /// Find a user by id /// /// /// public virtual Task FindByIdAsync(string userId) { ThrowIfDisposed(); return Store.FindByIdAsync(userId, CancellationToken); } /// /// Find a user by name /// /// /// public virtual Task FindByNameAsync(string userName) { ThrowIfDisposed(); if (userName == null) { throw new ArgumentNullException("userName"); } userName = NormalizeKey(userName); return Store.FindByNameAsync(userName, CancellationToken); } // IUserPasswordStore methods private IUserPasswordStore GetPasswordStore() { var cast = Store as IUserPasswordStore; if (cast == null) { throw new NotSupportedException(Resources.StoreNotIUserPasswordStore); } return cast; } /// /// Create a user and associates it with the given password /// /// /// /// public virtual async Task 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 UpdatePasswordHash(passwordStore, user, password); if (!result.Succeeded) { return result; } return await CreateAsync(user); } /// /// Normalize a key (user name, email) for uniqueness comparisons /// /// /// public virtual string NormalizeKey(string key) { return (KeyNormalizer == null) ? key : KeyNormalizer.Normalize(key); } /// /// Update the user's normalized user name /// /// /// public virtual async Task UpdateNormalizedUserNameAsync(TUser user) { var normalizedName = NormalizeKey(await GetUserNameAsync(user)); await Store.SetNormalizedUserNameAsync(user, normalizedName, CancellationToken); } /// /// Get the user's name /// /// /// public virtual async Task GetUserNameAsync(TUser user) { ThrowIfDisposed(); if (user == null) { throw new ArgumentNullException("user"); } return await Store.GetUserNameAsync(user, CancellationToken); } /// /// Set the user's name /// /// /// /// public virtual async Task SetUserNameAsync(TUser user, string userName) { ThrowIfDisposed(); if (user == null) { throw new ArgumentNullException("user"); } await UpdateUserName(user, userName); return await LogResultAsync(await UpdateUserAsync(user), user); } private async Task UpdateUserName(TUser user, string userName) { await Store.SetUserNameAsync(user, userName, CancellationToken); await UpdateNormalizedUserNameAsync(user); } /// /// Get the user's id /// /// /// public virtual async Task GetUserIdAsync(TUser user) { ThrowIfDisposed(); return await Store.GetUserIdAsync(user, CancellationToken); } /// /// Returns true if the password combination is valid for the user /// /// /// /// public virtual async Task 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); } return await LogResultAsync(result != PasswordVerificationResult.Failed, user); } /// /// Returns true if the user has a password /// /// /// public virtual async Task HasPasswordAsync(TUser user) { ThrowIfDisposed(); var passwordStore = GetPasswordStore(); if (user == null) { throw new ArgumentNullException("user"); } return await LogResultAsync(await passwordStore.HasPasswordAsync(user, CancellationToken), user); } /// /// Add a user password only if one does not already exist /// /// /// /// public virtual async Task AddPasswordAsync(TUser user, string password) { ThrowIfDisposed(); var passwordStore = GetPasswordStore(); if (user == null) { throw new ArgumentNullException("user"); } var hash = await passwordStore.GetPasswordHashAsync(user, CancellationToken); if (hash != null) { return await LogResultAsync(IdentityResult.Failed(ErrorDescriber.UserAlreadyHasPassword()), user); } var result = await UpdatePasswordHash(passwordStore, user, password); if (!result.Succeeded) { return await LogResultAsync(result, user); } return await LogResultAsync(await UpdateUserAsync(user), user); } /// /// Change a user password /// /// /// /// /// public virtual async Task ChangePasswordAsync(TUser user, string currentPassword, string newPassword) { ThrowIfDisposed(); var passwordStore = GetPasswordStore(); if (user == null) { throw new ArgumentNullException("user"); } if (await VerifyPasswordAsync(passwordStore, user, currentPassword) != PasswordVerificationResult.Failed) { var result = await UpdatePasswordHash(passwordStore, user, newPassword); if (!result.Succeeded) { return await LogResultAsync(result, user); } return await LogResultAsync(await UpdateUserAsync(user), user); } return await LogResultAsync(IdentityResult.Failed(ErrorDescriber.PasswordMismatch()), user); } /// /// Remove a user's password /// /// /// public virtual async Task RemovePasswordAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken)) { ThrowIfDisposed(); var passwordStore = GetPasswordStore(); if (user == null) { throw new ArgumentNullException("user"); } await UpdatePasswordHash(passwordStore, user, null, validatePassword: false); return await LogResultAsync(await UpdateUserAsync(user), user); } internal async Task UpdatePasswordHash(IUserPasswordStore passwordStore, TUser user, string newPassword, bool validatePassword = true) { if (validatePassword) { var validate = await ValidatePasswordInternal(user, newPassword); if (!validate.Succeeded) { return validate; } } var hash = newPassword != null ? PasswordHasher.HashPassword(user, newPassword) : null; await passwordStore.SetPasswordHashAsync(user, hash, CancellationToken); await UpdateSecurityStampInternal(user); return IdentityResult.Success; } /// /// By default, retrieves the hashed password from the user store and calls PasswordHasher.VerifyHashPassword /// /// /// /// /// protected virtual async Task VerifyPasswordAsync(IUserPasswordStore store, TUser user, string password) { var hash = await store.GetPasswordHashAsync(user, CancellationToken); return PasswordHasher.VerifyHashedPassword(user, hash, password); } // IUserSecurityStampStore methods private IUserSecurityStampStore GetSecurityStore() { var cast = Store as IUserSecurityStampStore; if (cast == null) { throw new NotSupportedException(Resources.StoreNotIUserSecurityStampStore); } return cast; } /// /// Returns the current security stamp for a user /// /// /// public virtual async Task GetSecurityStampAsync(TUser user) { ThrowIfDisposed(); var securityStore = GetSecurityStore(); if (user == null) { throw new ArgumentNullException("user"); } return await securityStore.GetSecurityStampAsync(user, CancellationToken); } /// /// Generate a new security stamp for a user, used for SignOutEverywhere functionality /// /// /// public virtual async Task UpdateSecurityStampAsync(TUser user) { ThrowIfDisposed(); GetSecurityStore(); if (user == null) { throw new ArgumentNullException("user"); } await UpdateSecurityStampInternal(user); return await LogResultAsync(await UpdateUserAsync(user), user); } /// /// GenerateAsync a password reset token for the user using the UserTokenProvider /// /// /// public virtual async Task GeneratePasswordResetTokenAsync(TUser user) { ThrowIfDisposed(); var token = await GenerateUserTokenAsync(user, Options.PasswordResetTokenProvider, "ResetPassword"); await LogResultAsync(IdentityResult.Success, user); return token; } /// /// Reset a user's password using a reset password token /// /// /// /// /// public virtual async Task ResetPasswordAsync(TUser user, string token, string newPassword) { ThrowIfDisposed(); if (user == null) { throw new ArgumentNullException("user"); } // Make sure the token is valid and the stamp matches if (!await VerifyUserTokenAsync(user, Options.PasswordResetTokenProvider, "ResetPassword", token)) { return await LogResultAsync(IdentityResult.Failed(ErrorDescriber.InvalidToken()), user); } var passwordStore = GetPasswordStore(); var result = await UpdatePasswordHash(passwordStore, user, newPassword); if (!result.Succeeded) { return await LogResultAsync(result, user); } return await LogResultAsync(await UpdateUserAsync(user), user); } // Update the security stamp if the store supports it internal async Task UpdateSecurityStampInternal(TUser user) { if (SupportsUserSecurityStamp) { await GetSecurityStore().SetSecurityStampAsync(user, NewSecurityStamp(), CancellationToken); } } private static string NewSecurityStamp() { return Guid.NewGuid().ToString(); } // IUserLoginStore methods private IUserLoginStore GetLoginStore() { var cast = Store as IUserLoginStore; if (cast == null) { throw new NotSupportedException(Resources.StoreNotIUserLoginStore); } return cast; } /// /// Returns the user associated with this login /// /// /// /// public virtual Task FindByLoginAsync(string loginProvider, string providerKey) { ThrowIfDisposed(); var loginStore = GetLoginStore(); if (loginProvider == null) { throw new ArgumentNullException("loginProvider"); } if (providerKey == null) { throw new ArgumentNullException("providerKey"); } return loginStore.FindByLoginAsync(loginProvider, providerKey, CancellationToken); } /// /// Remove a user login /// /// /// /// public virtual async Task RemoveLoginAsync(TUser user, string loginProvider, string providerKey) { ThrowIfDisposed(); var loginStore = GetLoginStore(); if (loginProvider == null) { throw new ArgumentNullException("loginProvider"); } if (providerKey == null) { throw new ArgumentNullException("providerKey"); } if (user == null) { throw new ArgumentNullException("user"); } await loginStore.RemoveLoginAsync(user, loginProvider, providerKey, CancellationToken); await UpdateSecurityStampInternal(user); return await LogResultAsync(await UpdateUserAsync(user), user); } /// /// Associate a login with a user /// /// /// /// public virtual async Task AddLoginAsync(TUser user, UserLoginInfo login) { ThrowIfDisposed(); var loginStore = GetLoginStore(); if (login == null) { throw new ArgumentNullException("login"); } if (user == null) { throw new ArgumentNullException("user"); } var existingUser = await FindByLoginAsync(login.LoginProvider, login.ProviderKey); if (existingUser != null) { return await LogResultAsync(IdentityResult.Failed(ErrorDescriber.LoginAlreadyAssociated()), user); } await loginStore.AddLoginAsync(user, login, CancellationToken); return await LogResultAsync(await UpdateUserAsync(user), user); } /// /// Gets the logins for a user. /// /// /// public virtual async Task> GetLoginsAsync(TUser user) { ThrowIfDisposed(); var loginStore = GetLoginStore(); if (user == null) { throw new ArgumentNullException("user"); } return await loginStore.GetLoginsAsync(user, CancellationToken); } // IUserClaimStore methods private IUserClaimStore GetClaimStore() { var cast = Store as IUserClaimStore; if (cast == null) { throw new NotSupportedException(Resources.StoreNotIUserClaimStore); } return cast; } /// /// Add a user claim /// /// /// /// public virtual Task AddClaimAsync(TUser user, Claim claim) { ThrowIfDisposed(); var claimStore = GetClaimStore(); if (claim == null) { throw new ArgumentNullException("claim"); } if (user == null) { throw new ArgumentNullException("user"); } return AddClaimsAsync(user, new Claim[] { claim }); } /// /// Add claims for a user /// /// /// /// public virtual async Task AddClaimsAsync(TUser user, IEnumerable claims) { ThrowIfDisposed(); var claimStore = GetClaimStore(); if (claims == null) { throw new ArgumentNullException("claims"); } if (user == null) { throw new ArgumentNullException("user"); } await claimStore.AddClaimsAsync(user, claims, CancellationToken); return await LogResultAsync(await UpdateUserAsync(user), user); } /// /// Updates the give claim information with the given new claim information /// /// /// /// /// public virtual async Task ReplaceClaimAsync(TUser user, Claim claim, Claim newClaim) { ThrowIfDisposed(); var claimStore = GetClaimStore(); if (claim == null) { throw new ArgumentNullException("claim"); } if (newClaim == null) { throw new ArgumentNullException("newClaim"); } if (user == null) { throw new ArgumentNullException("user"); } await claimStore.ReplaceClaimAsync(user, claim, newClaim, CancellationToken); return await LogResultAsync(await UpdateUserAsync(user), user); } /// /// Remove a user claim /// /// /// /// public virtual Task RemoveClaimAsync(TUser user, Claim claim) { ThrowIfDisposed(); var claimStore = GetClaimStore(); if (user == null) { throw new ArgumentNullException("user"); } if (claim == null) { throw new ArgumentNullException("claim"); } return RemoveClaimsAsync(user, new Claim[] { claim }); } /// /// Remove a user claim /// /// /// /// public virtual async Task RemoveClaimsAsync(TUser user, IEnumerable claims) { ThrowIfDisposed(); var claimStore = GetClaimStore(); if (user == null) { throw new ArgumentNullException("user"); } if (claims == null) { throw new ArgumentNullException("claims"); } await claimStore.RemoveClaimsAsync(user, claims, CancellationToken); return await LogResultAsync(await UpdateUserAsync(user), user); } /// /// Get a users's claims /// /// /// public virtual async Task> GetClaimsAsync(TUser user) { ThrowIfDisposed(); var claimStore = GetClaimStore(); if (user == null) { throw new ArgumentNullException("user"); } return await claimStore.GetClaimsAsync(user, CancellationToken); } private IUserRoleStore GetUserRoleStore() { var cast = Store as IUserRoleStore; if (cast == null) { throw new NotSupportedException(Resources.StoreNotIUserRoleStore); } return cast; } /// /// Add a user to a role /// /// /// /// public virtual async Task AddToRoleAsync(TUser user, string role) { ThrowIfDisposed(); var userRoleStore = GetUserRoleStore(); if (user == null) { throw new ArgumentNullException("user"); } var userRoles = await userRoleStore.GetRolesAsync(user, CancellationToken); if (userRoles.Contains(role)) { return await LogResultAsync(IdentityResult.Failed(ErrorDescriber.UserAlreadyInRole(role)), user); } await userRoleStore.AddToRoleAsync(user, role, CancellationToken); return await LogResultAsync(await UpdateUserAsync(user), user); } /// /// Add a user to roles /// /// /// /// public virtual async Task AddToRolesAsync(TUser user, IEnumerable roles) { ThrowIfDisposed(); var userRoleStore = GetUserRoleStore(); if (user == null) { throw new ArgumentNullException("user"); } if (roles == null) { throw new ArgumentNullException("roles"); } var userRoles = await userRoleStore.GetRolesAsync(user, CancellationToken); foreach (var role in roles) { if (userRoles.Contains(role)) { return await LogResultAsync(IdentityResult.Failed(ErrorDescriber.UserAlreadyInRole(role)), user); } await userRoleStore.AddToRoleAsync(user, role, CancellationToken); } return await LogResultAsync(await UpdateUserAsync(user), user); } /// /// Remove a user from a role. /// /// /// /// public virtual async Task RemoveFromRoleAsync(TUser user, string role) { ThrowIfDisposed(); var userRoleStore = GetUserRoleStore(); if (user == null) { throw new ArgumentNullException("user"); } if (!await userRoleStore.IsInRoleAsync(user, role, CancellationToken)) { return await LogResultAsync(IdentityResult.Failed(ErrorDescriber.UserNotInRole(role)), user); } await userRoleStore.RemoveFromRoleAsync(user, role, CancellationToken); return await LogResultAsync(await UpdateUserAsync(user), user); } /// /// Remove a user from a specified roles. /// /// /// /// public virtual async Task RemoveFromRolesAsync(TUser user, IEnumerable roles) { ThrowIfDisposed(); var userRoleStore = GetUserRoleStore(); if (user == null) { throw new ArgumentNullException("user"); } if (roles == null) { throw new ArgumentNullException("roles"); } foreach (var role in roles) { if (!await userRoleStore.IsInRoleAsync(user, role, CancellationToken)) { return await LogResultAsync(IdentityResult.Failed(ErrorDescriber.UserNotInRole(role)), user); } await userRoleStore.RemoveFromRoleAsync(user, role, CancellationToken); } return await LogResultAsync(await UpdateUserAsync(user), user); } /// /// Returns the roles for the user /// /// /// public virtual async Task> GetRolesAsync(TUser user) { ThrowIfDisposed(); var userRoleStore = GetUserRoleStore(); if (user == null) { throw new ArgumentNullException("user"); } return await userRoleStore.GetRolesAsync(user, CancellationToken); } /// /// Returns true if the user is in the specified role /// /// /// /// public virtual async Task IsInRoleAsync(TUser user, string role) { ThrowIfDisposed(); var userRoleStore = GetUserRoleStore(); if (user == null) { throw new ArgumentNullException("user"); } return await userRoleStore.IsInRoleAsync(user, role, CancellationToken); } // IUserEmailStore methods internal IUserEmailStore GetEmailStore(bool throwOnFail = true) { var cast = Store as IUserEmailStore; if (throwOnFail && cast == null) { throw new NotSupportedException(Resources.StoreNotIUserEmailStore); } return cast; } /// /// Get a user's email /// /// /// public virtual async Task GetEmailAsync(TUser user) { ThrowIfDisposed(); var store = GetEmailStore(); if (user == null) { throw new ArgumentNullException("user"); } return await store.GetEmailAsync(user, CancellationToken); } /// /// Set a user's email /// /// /// /// public virtual async Task SetEmailAsync(TUser user, string email) { ThrowIfDisposed(); var store = GetEmailStore(); if (user == null) { throw new ArgumentNullException("user"); } await store.SetEmailAsync(user, email, CancellationToken); await store.SetEmailConfirmedAsync(user, false, CancellationToken); await UpdateSecurityStampInternal(user); return await LogResultAsync(await UpdateUserAsync(user), user); } /// /// FindByLoginAsync a user by his email /// /// /// public virtual Task FindByEmailAsync(string email) { ThrowIfDisposed(); var store = GetEmailStore(); if (email == null) { throw new ArgumentNullException("email"); } return store.FindByEmailAsync(NormalizeKey(email), CancellationToken); } /// /// Update the user's normalized email /// /// /// public virtual async Task UpdateNormalizedEmailAsync(TUser user) { var store = GetEmailStore(throwOnFail: false); if (store != null) { var email = await GetEmailAsync(user); await store.SetNormalizedEmailAsync(user, NormalizeKey(email), CancellationToken); } } /// /// Get the confirmation token for the user /// /// /// public async virtual Task GenerateEmailConfirmationTokenAsync(TUser user) { ThrowIfDisposed(); var token = await GenerateUserTokenAsync(user, Options.EmailConfirmationTokenProvider, "Confirmation"); await LogResultAsync(IdentityResult.Success, user); return token; } /// /// Confirm the user with confirmation token /// /// /// /// public virtual async Task ConfirmEmailAsync(TUser user, string token) { ThrowIfDisposed(); var store = GetEmailStore(); if (user == null) { throw new ArgumentNullException("user"); } if (!await VerifyUserTokenAsync(user, Options.EmailConfirmationTokenProvider, "Confirmation", token)) { return await LogResultAsync(IdentityResult.Failed(ErrorDescriber.InvalidToken()), user); } await store.SetEmailConfirmedAsync(user, true, CancellationToken); return await LogResultAsync(await UpdateUserAsync(user), user); } /// /// Returns true if the user's email has been confirmed /// /// /// public virtual async Task IsEmailConfirmedAsync(TUser user) { ThrowIfDisposed(); var store = GetEmailStore(); if (user == null) { throw new ArgumentNullException("user"); } return await store.GetEmailConfirmedAsync(user, CancellationToken); } private static string GetChangeEmailPurpose(string newEmail) { return "ChangeEmail:" + newEmail; } /// /// Generate a change email token for the user using the UserTokenProvider /// /// /// public virtual async Task GenerateChangeEmailTokenAsync(TUser user, string newEmail) { ThrowIfDisposed(); var token = await GenerateUserTokenAsync(user, Options.ChangeEmailTokenProvider, GetChangeEmailPurpose(newEmail)); await LogResultAsync(IdentityResult.Success, user); return token; } /// /// Change a user's email using a change email token /// /// /// /// /// public virtual async Task ChangeEmailAsync(TUser user, string newEmail, string token) { ThrowIfDisposed(); if (user == null) { throw new ArgumentNullException("user"); } // Make sure the token is valid and the stamp matches if (!await VerifyUserTokenAsync(user, Options.ChangeEmailTokenProvider, GetChangeEmailPurpose(newEmail), token)) { return await LogResultAsync(IdentityResult.Failed(ErrorDescriber.InvalidToken()), user); } var store = GetEmailStore(); await store.SetEmailAsync(user, newEmail, CancellationToken); await store.SetEmailConfirmedAsync(user, true, CancellationToken); await UpdateSecurityStampInternal(user); return await LogResultAsync(await UpdateUserAsync(user), user); } // IUserPhoneNumberStore methods internal IUserPhoneNumberStore GetPhoneNumberStore() { var cast = Store as IUserPhoneNumberStore; if (cast == null) { throw new NotSupportedException(Resources.StoreNotIUserPhoneNumberStore); } return cast; } /// /// Get a user's phoneNumber /// /// /// public virtual async Task GetPhoneNumberAsync(TUser user) { ThrowIfDisposed(); var store = GetPhoneNumberStore(); if (user == null) { throw new ArgumentNullException("user"); } return await store.GetPhoneNumberAsync(user, CancellationToken); } /// /// Set a user's phoneNumber /// /// /// /// public virtual async Task SetPhoneNumberAsync(TUser user, string phoneNumber) { ThrowIfDisposed(); var store = GetPhoneNumberStore(); if (user == null) { throw new ArgumentNullException("user"); } await store.SetPhoneNumberAsync(user, phoneNumber, CancellationToken); await store.SetPhoneNumberConfirmedAsync(user, false, CancellationToken); await UpdateSecurityStampInternal(user); return await LogResultAsync(await UpdateUserAsync(user), user); } /// /// Set a user's phoneNumber with the verification token /// /// /// /// /// public virtual async Task ChangePhoneNumberAsync(TUser user, string phoneNumber, string token) { ThrowIfDisposed(); var store = GetPhoneNumberStore(); if (user == null) { throw new ArgumentNullException("user"); } if (!await VerifyChangePhoneNumberTokenAsync(user, token, phoneNumber)) { return await LogResultAsync(IdentityResult.Failed(ErrorDescriber.InvalidToken()), user); } await store.SetPhoneNumberAsync(user, phoneNumber, CancellationToken); await store.SetPhoneNumberConfirmedAsync(user, true, CancellationToken); await UpdateSecurityStampInternal(user); return await LogResultAsync(await UpdateUserAsync(user), user); } /// /// Returns true if the user's phone number has been confirmed /// /// /// public virtual async Task IsPhoneNumberConfirmedAsync(TUser user) { ThrowIfDisposed(); var store = GetPhoneNumberStore(); if (user == null) { throw new ArgumentNullException("user"); } return await store.GetPhoneNumberConfirmedAsync(user, CancellationToken); } // Two factor APIS internal async Task CreateSecurityTokenAsync(TUser user) { return new SecurityToken(Encoding.Unicode.GetBytes(await GetSecurityStampAsync(user))); } /// /// Get a phone number code for a user and phone number /// /// /// /// public virtual async Task GenerateChangePhoneNumberTokenAsync(TUser user, string phoneNumber) { ThrowIfDisposed(); var token = Rfc6238AuthenticationService.GenerateCode( await CreateSecurityTokenAsync(user), phoneNumber) .ToString(CultureInfo.InvariantCulture); await LogResultAsync(IdentityResult.Success, user); return token; } /// /// Verify a phone number code for a specific user and phone number /// /// /// /// /// public virtual async Task VerifyChangePhoneNumberTokenAsync(TUser user, string token, string phoneNumber) { ThrowIfDisposed(); var securityToken = await CreateSecurityTokenAsync(user); int code; if (securityToken != null && Int32.TryParse(token, out code)) { if (Rfc6238AuthenticationService.ValidateCode(securityToken, code, phoneNumber)) { await LogResultAsync(IdentityResult.Success, user); return true; } } await LogResultAsync(IdentityResult.Failed(ErrorDescriber.InvalidToken()), user); return false; } /// /// Verify a user token with the specified purpose /// /// /// /// /// public virtual async Task VerifyUserTokenAsync(TUser user, string tokenProvider, string purpose, string token) { ThrowIfDisposed(); if (user == null) { throw new ArgumentNullException("user"); } if (tokenProvider == null) { throw new ArgumentNullException(nameof(tokenProvider)); } if (!_tokenProviders.ContainsKey(tokenProvider)) { throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, Resources.NoTokenProvider, tokenProvider)); } // Make sure the token is valid var result = await _tokenProviders[tokenProvider].ValidateAsync(purpose, token, this, user); if (result) { await LogResultAsync(IdentityResult.Success, user); } else { await LogResultAsync(IdentityResult.Failed(ErrorDescriber.InvalidToken()), user); } return result; } /// /// Get a user token for a specific purpose /// /// /// /// public virtual async Task GenerateUserTokenAsync(TUser user, string tokenProvider, string purpose) { ThrowIfDisposed(); if (user == null) { throw new ArgumentNullException("user"); } if (tokenProvider == null) { throw new ArgumentNullException(nameof(tokenProvider)); } if (!_tokenProviders.ContainsKey(tokenProvider)) { throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, Resources.NoTokenProvider, tokenProvider)); } var token = await _tokenProviders[tokenProvider].GenerateAsync(purpose, this, user); await LogResultAsync(IdentityResult.Success, user); return token; } /// /// Register a user token provider /// /// public virtual void RegisterTokenProvider(IUserTokenProvider provider) { ThrowIfDisposed(); if (provider == null) { throw new ArgumentNullException("provider"); } _tokenProviders[provider.Name] = provider; } /// /// Returns a list of valid two factor providers for a user /// /// /// public virtual async Task> GetValidTwoFactorProvidersAsync(TUser user) { ThrowIfDisposed(); if (user == null) { throw new ArgumentNullException("user"); } var results = new List(); foreach (var f in _tokenProviders) { if (await f.Value.CanGenerateTwoFactorTokenAsync(this, user)) { results.Add(f.Key); } } return results; } /// /// Verify a user token with the specified provider /// /// /// /// /// public virtual async Task VerifyTwoFactorTokenAsync(TUser user, string tokenProvider, string token) { ThrowIfDisposed(); if (user == null) { throw new ArgumentNullException("user"); } if (!_tokenProviders.ContainsKey(tokenProvider)) { throw new NotSupportedException(String.Format(CultureInfo.CurrentCulture, Resources.NoTokenProvider, tokenProvider)); } // Make sure the token is valid var result = await _tokenProviders[tokenProvider].ValidateAsync("TwoFactor", token, this, user); if (result) { await LogResultAsync(IdentityResult.Success, user); } else { await LogResultAsync(IdentityResult.Failed(ErrorDescriber.InvalidToken()), user); } return result; } /// /// Get a user token for a specific user factor provider /// /// /// /// public virtual async Task GenerateTwoFactorTokenAsync(TUser user, string tokenProvider) { ThrowIfDisposed(); if (user == null) { throw new ArgumentNullException("user"); } if (!_tokenProviders.ContainsKey(tokenProvider)) { throw new NotSupportedException(String.Format(CultureInfo.CurrentCulture, Resources.NoTokenProvider, tokenProvider)); } var token = await _tokenProviders[tokenProvider].GenerateAsync("TwoFactor", this, user); await LogResultAsync(IdentityResult.Success, user); return token; } // IUserFactorStore methods internal IUserTwoFactorStore GetUserTwoFactorStore() { var cast = Store as IUserTwoFactorStore; if (cast == null) { throw new NotSupportedException(Resources.StoreNotIUserTwoFactorStore); } return cast; } /// /// Get a user's two factor provider /// /// /// public virtual async Task GetTwoFactorEnabledAsync(TUser user) { ThrowIfDisposed(); var store = GetUserTwoFactorStore(); if (user == null) { throw new ArgumentNullException("user"); } return await store.GetTwoFactorEnabledAsync(user, CancellationToken); } /// /// Set whether a user has two factor enabled or not /// /// /// /// public virtual async Task SetTwoFactorEnabledAsync(TUser user, bool enabled) { ThrowIfDisposed(); var store = GetUserTwoFactorStore(); if (user == null) { throw new ArgumentNullException("user"); } await store.SetTwoFactorEnabledAsync(user, enabled, CancellationToken); await UpdateSecurityStampInternal(user); return await LogResultAsync(await UpdateUserAsync(user), user); } // IUserLockoutStore methods internal IUserLockoutStore GetUserLockoutStore() { var cast = Store as IUserLockoutStore; if (cast == null) { throw new NotSupportedException(Resources.StoreNotIUserLockoutStore); } return cast; } /// /// Returns true if the user is locked out /// /// /// public virtual async Task IsLockedOutAsync(TUser user) { ThrowIfDisposed(); var store = GetUserLockoutStore(); if (user == null) { throw new ArgumentNullException("user"); } if (!await store.GetLockoutEnabledAsync(user, CancellationToken)) { return false; } var lockoutTime = await store.GetLockoutEndDateAsync(user, CancellationToken); return lockoutTime >= DateTimeOffset.UtcNow; } /// /// Sets whether the user allows lockout /// /// /// /// public virtual async Task SetLockoutEnabledAsync(TUser user, bool enabled) { ThrowIfDisposed(); var store = GetUserLockoutStore(); if (user == null) { throw new ArgumentNullException("user"); } await store.SetLockoutEnabledAsync(user, enabled, CancellationToken); return await LogResultAsync(await UpdateUserAsync(user), user); } /// /// Returns whether the user allows lockout /// /// /// public virtual async Task GetLockoutEnabledAsync(TUser user) { ThrowIfDisposed(); var store = GetUserLockoutStore(); if (user == null) { throw new ArgumentNullException("user"); } return await store.GetLockoutEnabledAsync(user, CancellationToken); } /// /// Returns the user lockout end date /// /// /// public virtual async Task GetLockoutEndDateAsync(TUser user) { ThrowIfDisposed(); var store = GetUserLockoutStore(); if (user == null) { throw new ArgumentNullException("user"); } return await store.GetLockoutEndDateAsync(user, CancellationToken); } /// /// Sets the user lockout end date /// /// /// /// public virtual async Task SetLockoutEndDateAsync(TUser user, DateTimeOffset? lockoutEnd) { ThrowIfDisposed(); var store = GetUserLockoutStore(); if (user == null) { throw new ArgumentNullException("user"); } if (!await store.GetLockoutEnabledAsync(user, CancellationToken)) { return await LogResultAsync(IdentityResult.Failed(ErrorDescriber.UserLockoutNotEnabled()), user); } await store.SetLockoutEndDateAsync(user, lockoutEnd, CancellationToken); return await LogResultAsync(await UpdateUserAsync(user), user); } /// /// Increments the access failed count for the user and if the failed access account is greater than or equal /// to the MaxFailedAccessAttempsBeforeLockout, the user will be locked out for the next /// DefaultAccountLockoutTimeSpan and the AccessFailedCount will be reset to 0. /// /// /// public virtual async Task AccessFailedAsync(TUser user) { ThrowIfDisposed(); var store = GetUserLockoutStore(); if (user == null) { throw new ArgumentNullException("user"); } // If this puts the user over the threshold for lockout, lock them out and reset the access failed count var count = await store.IncrementAccessFailedCountAsync(user, CancellationToken); if (count < Options.Lockout.MaxFailedAccessAttempts) { return await LogResultAsync(await UpdateUserAsync(user), user); } await store.SetLockoutEndDateAsync(user, DateTimeOffset.UtcNow.Add(Options.Lockout.DefaultLockoutTimeSpan), CancellationToken); await store.ResetAccessFailedCountAsync(user, CancellationToken); return await LogResultAsync(await UpdateUserAsync(user), user); } /// /// Resets the access failed count for the user to 0 /// /// /// public virtual async Task ResetAccessFailedCountAsync(TUser user) { ThrowIfDisposed(); var store = GetUserLockoutStore(); if (user == null) { throw new ArgumentNullException("user"); } if (await GetAccessFailedCountAsync(user) == 0) { return IdentityResult.Success; } await store.ResetAccessFailedCountAsync(user, CancellationToken); return await LogResultAsync(await UpdateUserAsync(user), user); } /// /// Returns the number of failed access attempts for the user /// /// /// public virtual async Task GetAccessFailedCountAsync(TUser user) { ThrowIfDisposed(); var store = GetUserLockoutStore(); if (user == null) { throw new ArgumentNullException("user"); } return await store.GetAccessFailedCountAsync(user, CancellationToken); } public virtual Task> GetUsersForClaimAsync(Claim claim) { ThrowIfDisposed(); var store = GetClaimStore(); if (claim == null) { throw new ArgumentNullException("claim"); } return store.GetUsersForClaimAsync(claim, CancellationToken); } /// /// Get all the users in a role /// /// /// public virtual Task> GetUsersInRoleAsync(string roleName) { ThrowIfDisposed(); var store = GetUserRoleStore(); if (roleName == null) { throw new ArgumentNullException("role"); } return store.GetUsersInRoleAsync(roleName, CancellationToken); } /// /// Logs the current Identity Result and returns result object /// /// /// /// /// protected async Task LogResultAsync(IdentityResult result, TUser user, [System.Runtime.CompilerServices.CallerMemberName] string methodName = "") { result.Log(Logger, Resources.FormatLoggingResultMessage(methodName, await GetUserIdAsync(user))); return result; } /// /// Logs result of operation being true/false /// /// /// /// /// result protected async Task LogResultAsync(bool result, TUser user, [System.Runtime.CompilerServices.CallerMemberName] string methodName = "") { var baseMessage = Resources.FormatLoggingResultMessage(methodName, await GetUserIdAsync(user)); if (result) { Logger.LogInformation(string.Format("{0} : {1}", baseMessage, result.ToString())); } else { Logger.LogWarning(string.Format("{0} : {1}", baseMessage, result.ToString())); } return result; } private void ThrowIfDisposed() { if (_disposed) { throw new ObjectDisposedException(GetType().Name); } } /// /// When disposing, actually dipose the store context /// /// protected virtual void Dispose(bool disposing) { if (disposing && !_disposed) { Store.Dispose(); _disposed = true; } } } }