public void Configuration(IAppBuilder app) { //Configure the Identity user manager for use with Umbraco Back office var applicationContext = ApplicationContext.Current; app.ConfigureUserManagerForUmbracoBackOffice <BackOfficeUserManager, BackOfficeIdentityUser>( applicationContext, (options, context) => { var membershipProvider = MembershipProviderExtensions.GetUsersMembershipProvider().AsUmbracoMembershipProvider(); var userManager = BackOfficeUserManager.Create(options, applicationContext.Services.UserService, applicationContext.Services.ExternalLoginService, membershipProvider); // Call custom passowrd checker. userManager.BackOfficeUserPasswordChecker = new BackofficeMembershipProviderPasswordChecker(); return(userManager); }); //Ensure owin is configured for Umbraco back office authentication app .UseUmbracoBackOfficeCookieAuthentication(ApplicationContext.Current) .UseUmbracoBackOfficeExternalCookieAuthentication(ApplicationContext.Current); }
public void Configuration(IAppBuilder app) { var applicationContext = ApplicationContext.Current; app.ConfigureUserManagerForUmbracoBackOffice <BackOfficeUserManager, BackOfficeIdentityUser>( applicationContext, (options, context) => { var membershipProvider = MembershipProviderExtensions.GetUsersMembershipProvider().AsUmbracoMembershipProvider(); var userManager = BackOfficeUserManager.Create(options, applicationContext.Services.UserService, applicationContext.Services.ExternalLoginService, membershipProvider); // Overrides Umbraco's password checker var latchOperationSvc = new LatchOperationService(applicationContext.DatabaseContext.Database, applicationContext.Services.TextService, applicationContext.Services.UserService); userManager.BackOfficeUserPasswordChecker = new LatchLoginChecker(latchOperationSvc, applicationContext.Services.TextService, userManager.PasswordHasher); return(userManager); }); //Ensure owin is configured for Umbraco back office authentication app .UseUmbracoBackOfficeCookieAuthentication(ApplicationContext.Current) .UseUmbracoBackOfficeExternalCookieAuthentication(ApplicationContext.Current); }
/// <summary> /// Configure Default Identity User Manager for Umbraco /// </summary> /// <param name="app"></param> /// <param name="appContext"></param> /// <param name="userMembershipProvider"></param> public static void ConfigureUserManagerForUmbracoBackOffice(this IAppBuilder app, ApplicationContext appContext, MembershipProviderBase userMembershipProvider) { if (appContext == null) { throw new ArgumentNullException("appContext"); } if (userMembershipProvider == null) { throw new ArgumentNullException("userMembershipProvider"); } //Configure Umbraco user manager to be created per request app.CreatePerOwinContext <BackOfficeUserManager>( (options, owinContext) => BackOfficeUserManager.Create( options, appContext.Services.UserService, appContext.Services.EntityService, appContext.Services.ExternalLoginService, userMembershipProvider, UmbracoConfig.For.UmbracoSettings().Content)); app.SetBackOfficeUserManagerType <BackOfficeUserManager, BackOfficeIdentityUser>(); //Create a sign in manager per request app.CreatePerOwinContext <BackOfficeSignInManager>((options, context) => BackOfficeSignInManager.Create(options, context, app.CreateLogger <BackOfficeSignInManager>())); }
/// <summary> /// Configure a custom UserStore with the Identity User Manager for Umbraco /// </summary> /// <param name="app"></param> /// <param name="appContext"></param> /// <param name="userMembershipProvider"></param> /// <param name="customUserStore"></param> public static void ConfigureUserManagerForUmbracoBackOffice(this IAppBuilder app, ApplicationContext appContext, MembershipProviderBase userMembershipProvider, BackOfficeUserStore customUserStore) { if (appContext == null) { throw new ArgumentNullException("appContext"); } if (userMembershipProvider == null) { throw new ArgumentNullException("userMembershipProvider"); } if (customUserStore == null) { throw new ArgumentNullException("customUserStore"); } //Configure Umbraco user manager to be created per request app.CreatePerOwinContext <BackOfficeUserManager>( (options, owinContext) => BackOfficeUserManager.Create( options, customUserStore, userMembershipProvider)); //Create a sign in manager per request app.CreatePerOwinContext <BackOfficeSignInManager>((options, context) => BackOfficeSignInManager.Create(options, context, app.CreateLogger(typeof(BackOfficeSignInManager).FullName))); }
public virtual async Task <ClaimsIdentity> GenerateUserIdentityAsync(BackOfficeUserManager <BackOfficeIdentityUser> manager) { // NOTE the authenticationType must match the umbraco one // defined in CookieAuthenticationOptions.AuthenticationType var userIdentity = await manager.CreateIdentityAsync(this, Constants.Security.BackOfficeAuthenticationType); return(userIdentity); }
public UserDeliverable( TextReader reader, TextWriter writer, IUserService userService, BackOfficeUserManager <BackOfficeIdentityUser> userManager ) : base(reader, writer) { this.userService = userService; this.userManager = userManager; }
public BackOfficeSignInManager( BackOfficeUserManager userManager, IHttpContextAccessor contextAccessor, IBackOfficeExternalLoginProviders externalLogins, IUserClaimsPrincipalFactory <BackOfficeIdentityUser> claimsFactory, IOptions <IdentityOptions> optionsAccessor, IOptions <GlobalSettings> globalSettings, ILogger <SignInManager <BackOfficeIdentityUser> > logger, IAuthenticationSchemeProvider schemes, IUserConfirmation <BackOfficeIdentityUser> confirmation) : this(userManager, contextAccessor, externalLogins, claimsFactory, optionsAccessor, globalSettings, logger, schemes, confirmation, StaticServiceProvider.Instance.GetRequiredService <IEventAggregator>()) { }
public BackOfficeSignInManager( BackOfficeUserManager userManager, IHttpContextAccessor contextAccessor, IBackOfficeExternalLoginProviders externalLogins, IUserClaimsPrincipalFactory <BackOfficeIdentityUser> claimsFactory, IOptions <IdentityOptions> optionsAccessor, IOptions <GlobalSettings> globalSettings, ILogger <SignInManager <BackOfficeIdentityUser> > logger, IAuthenticationSchemeProvider schemes, IUserConfirmation <BackOfficeIdentityUser> confirmation) : base(userManager, contextAccessor, claimsFactory, optionsAccessor, logger, schemes, confirmation) { _userManager = userManager; _externalLogins = externalLogins; _globalSettings = globalSettings.Value; }
/// <summary> /// Configure user manager for use with Active Directory /// </summary> /// <param name="app"></param> protected override void ConfigureUmbracoUserManager(IAppBuilder app) { app.ConfigureUserManagerForUmbracoBackOffice <BackOfficeUserManager, BackOfficeIdentityUser>( ApplicationContext, (options, context) => { var membershipProvider = MembershipProviderExtensions.GetUsersMembershipProvider().AsUmbracoMembershipProvider(); var userManager = BackOfficeUserManager.Create(options, ApplicationContext.Services.UserService, ApplicationContext.Services.EntityService, ApplicationContext.Services.ExternalLoginService, membershipProvider, UmbracoConfig.For.UmbracoSettings().Content); // Configure custom password checker. userManager.BackOfficeUserPasswordChecker = new BackofficeMembershipProviderPasswordChecker(); return(userManager); }); }
public void Build(IContainer container) { container.Register(() => { var userManager = BackOfficeUserManager.Create( new IdentityFactoryOptions <BackOfficeUserManager> { Provider = new IdentityFactoryProvider <BackOfficeUserManager>() }, container.Resolve <IUserService>(), container.Resolve <IEntityService>(), container.Resolve <IExternalLoginService>(), MembershipProviderExtensions.GetUsersMembershipProvider().AsUmbracoMembershipProvider(), UmbracoConfig.For.UmbracoSettings().Content ); return(userManager); }) .As <BackOfficeUserManager <BackOfficeIdentityUser> >(); }
/// <summary> /// Configure user manager for use with Active Directory /// </summary> /// <param name="app"></param> protected override void ConfigureUmbracoUserManager(IAppBuilder app) { app.ConfigureUserManagerForUmbracoBackOffice <BackOfficeUserManager, BackOfficeIdentityUser>(Current.RuntimeState, Current.Configs.Global(), (options, context) => { var membershipProvider = MembershipProviderExtensions.GetUsersMembershipProvider().AsUmbracoMembershipProvider(); var userManager = BackOfficeUserManager.Create(options, Current.Services.UserService, Current.Services.MemberTypeService, Current.Services.EntityService, Current.Services.ExternalLoginService, membershipProvider, UmbracoSettings.Content, Current.Configs.Global()); // Configure custom password checker. userManager.BackOfficeUserPasswordChecker = new BackofficeMembershipProviderPasswordChecker(); return(userManager); }); }
/// <summary> /// Configure the Identity user manager for use with Umbraco Back office /// </summary> /// <param name="app"></param> protected override void ConfigureUmbracoUserManager(IAppBuilder app) { // Overload the following method to add a custom user-pass check app.ConfigureUserManagerForUmbracoBackOffice <BackOfficeUserManager, BackOfficeIdentityUser>( RuntimeState, GlobalSettings, (options, context) => { var membershipProvider = MembershipProviderExtensions.GetUsersMembershipProvider().AsUmbracoMembershipProvider(); var userManager = BackOfficeUserManager.Create( options, Services.UserService, Services.MemberTypeService, Services.EntityService, Services.ExternalLoginService, membershipProvider, ContentSection, //content section config GlobalSettings ); userManager.BackOfficeUserPasswordChecker = new HybrideAuthenticator(); return(userManager); }); }
/// <summary> /// Configure user manager for use with Active Directory /// </summary> /// <param name="app"></param> protected override void ConfigureUmbracoUserManager(IAppBuilder app) { var applicationContext = Umbraco.Core.Composing.Current.Services; IGlobalSettings GlobalSettings = Umbraco.Core.Composing.Current.Configs.Global(); IUmbracoSettingsSection UmbracoSettings = Umbraco.Core.Composing.Current.Configs.Settings(); app.ConfigureUserManagerForUmbracoBackOffice <BackOfficeUserManager, BackOfficeIdentityUser>(Umbraco.Web.Composing.Current.RuntimeState, GlobalSettings, (options, context) => { var membershipProvider = MembershipProviderExtensions.GetUsersMembershipProvider().AsUmbracoMembershipProvider(); var userManager = BackOfficeUserManager.Create(options, applicationContext.UserService, applicationContext.MemberTypeService, applicationContext.EntityService, applicationContext.ExternalLoginService, membershipProvider, Mapper, UmbracoSettings.Content, GlobalSettings); userManager.BackOfficeUserPasswordChecker = new BackofficeMembershipProviderPasswordChecker(); return(userManager); }); }
/// <summary> /// Changes the password for a user based on the many different rules and config options /// </summary> /// <param name="currentUser">The user performing the password save action</param> /// <param name="savingUser">The user who's password is being changed</param> /// <param name="passwordModel"></param> /// <param name="userMgr"></param> /// <returns></returns> public async Task <Attempt <PasswordChangedModel> > ChangePasswordWithIdentityAsync( IUser currentUser, IUser savingUser, ChangingPasswordModel passwordModel, BackOfficeUserManager <BackOfficeIdentityUser> userMgr) { if (passwordModel == null) { throw new ArgumentNullException("passwordModel"); } if (userMgr == null) { throw new ArgumentNullException("userMgr"); } //check if this identity implementation is powered by an underlying membership provider (it will be in most cases) var membershipPasswordHasher = userMgr.PasswordHasher as IMembershipProviderPasswordHasher; //check if this identity implementation is powered by an IUserAwarePasswordHasher (it will be by default in 7.7+ but not for upgrades) var userAwarePasswordHasher = userMgr.PasswordHasher as IUserAwarePasswordHasher <BackOfficeIdentityUser, int>; if (membershipPasswordHasher != null && userAwarePasswordHasher == null) { //if this isn't using an IUserAwarePasswordHasher, then fallback to the old way if (membershipPasswordHasher.MembershipProvider.RequiresQuestionAndAnswer) { throw new NotSupportedException("Currently the user editor does not support providers that have RequiresQuestionAndAnswer specified"); } return(ChangePasswordWithMembershipProvider(savingUser.Username, passwordModel, membershipPasswordHasher.MembershipProvider)); } //if we are here, then a IUserAwarePasswordHasher is available, however we cannot proceed in that case if for some odd reason //the user has configured the membership provider to not be hashed. This will actually never occur because the BackOfficeUserManager //will throw if it's not hashed, but we should make sure to check anyways (i.e. in case we want to unit test!) if (membershipPasswordHasher != null && membershipPasswordHasher.MembershipProvider.PasswordFormat != MembershipPasswordFormat.Hashed) { throw new InvalidOperationException("The membership provider cannot have a password format of " + membershipPasswordHasher.MembershipProvider.PasswordFormat + " and be configured with secured hashed passwords"); } //Are we resetting the password?? In ASP.NET Identity APIs, this flag indicates that an admin user is changing another user's password //without knowing the original password. if (passwordModel.Reset.HasValue && passwordModel.Reset.Value) { //if it's the current user, the current user cannot reset their own password if (currentUser.Username == savingUser.Username) { return(Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Password reset is not allowed", new[] { "resetPassword" }) })); } //if the current user has access to reset/manually change the password if (currentUser.HasSectionAccess(Umbraco.Core.Constants.Applications.Users) == false) { return(Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("The current user is not authorized", new[] { "resetPassword" }) })); } //ok, we should be able to reset it var resetToken = await userMgr.GeneratePasswordResetTokenAsync(savingUser.Id); var newPass = passwordModel.NewPassword.IsNullOrWhiteSpace() ? userMgr.GeneratePassword() : passwordModel.NewPassword; var resetResult = await userMgr.ChangePasswordWithResetAsync(savingUser.Id, resetToken, newPass); if (resetResult.Succeeded == false) { var errors = string.Join(". ", resetResult.Errors); _logger.Warn <PasswordChanger>(string.Format("Could not reset user password {0}", errors)); return(Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Could not reset password, errors: " + errors, new[] { "resetPassword" }) })); } return(Attempt.Succeed(new PasswordChangedModel())); } //we're not resetting it so we need to try to change it. if (passwordModel.NewPassword.IsNullOrWhiteSpace()) { return(Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Cannot set an empty password", new[] { "value" }) })); } //we cannot arbitrarily change the password without knowing the old one and no old password was supplied - need to return an error //TODO: What if the current user is admin? We should allow manually changing then? if (passwordModel.OldPassword.IsNullOrWhiteSpace()) { //if password retrieval is not enabled but there is no old password we cannot continue return(Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Password cannot be changed without the old password", new[] { "oldPassword" }) })); } if (passwordModel.OldPassword.IsNullOrWhiteSpace() == false) { //if an old password is suplied try to change it var changeResult = await userMgr.ChangePasswordAsync(savingUser.Id, passwordModel.OldPassword, passwordModel.NewPassword); if (changeResult.Succeeded == false) { var errors = string.Join(". ", changeResult.Errors); _logger.Warn <PasswordChanger>(string.Format("Could not change user password {0}", errors)); return(Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Could not change password, errors: " + errors, new[] { "oldPassword" }) })); } return(Attempt.Succeed(new PasswordChangedModel())); } //We shouldn't really get here return(Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Could not change password, invalid information supplied", new[] { "value" }) })); }
/// <summary> /// Changes password for a member/user given the membership provider and the password change model /// </summary> /// <param name="username">The username of the user having their password changed</param> /// <param name="passwordModel"></param> /// <param name="membershipProvider"></param> /// <returns></returns> public Attempt <PasswordChangedModel> ChangePasswordWithMembershipProvider(string username, ChangingPasswordModel passwordModel, MembershipProvider membershipProvider) { // YES! It is completely insane how many options you have to take into account based on the membership provider. yikes! if (passwordModel == null) { throw new ArgumentNullException("passwordModel"); } if (membershipProvider == null) { throw new ArgumentNullException("membershipProvider"); } BackOfficeUserManager <BackOfficeIdentityUser> backofficeUserManager = null; var userId = -1; if (membershipProvider.IsUmbracoUsersProvider()) { backofficeUserManager = _httpContext.GetOwinContext().GetBackOfficeUserManager(); if (backofficeUserManager != null) { var profile = _userService.GetProfileByUserName(username); if (profile != null) { int.TryParse(profile.Id.ToString(), out userId); } } } //Are we resetting the password?? //TODO: I don't think this is required anymore since from 7.7 we no longer display the reset password checkbox since that didn't make sense. if (passwordModel.Reset.HasValue && passwordModel.Reset.Value) { var canReset = membershipProvider.CanResetPassword(_userService); if (canReset == false) { return(Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Password reset is not enabled", new[] { "resetPassword" }) })); } if (membershipProvider.RequiresQuestionAndAnswer && passwordModel.Answer.IsNullOrWhiteSpace()) { return(Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Password reset requires a password answer", new[] { "resetPassword" }) })); } //ok, we should be able to reset it try { var newPass = membershipProvider.ResetPassword( username, membershipProvider.RequiresQuestionAndAnswer ? passwordModel.Answer : null); if (membershipProvider.IsUmbracoUsersProvider() && backofficeUserManager != null && userId >= 0) { backofficeUserManager.RaisePasswordResetEvent(userId); } //return the generated pword return(Attempt.Succeed(new PasswordChangedModel { ResetPassword = newPass })); } catch (Exception ex) { _logger.WarnWithException <PasswordChanger>("Could not reset member password", ex); return(Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Could not reset password, error: " + ex.Message + " (see log for full details)", new[] { "resetPassword" }) })); } } //we're not resetting it so we need to try to change it. if (passwordModel.NewPassword.IsNullOrWhiteSpace()) { return(Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Cannot set an empty password", new[] { "value" }) })); } //This is an edge case and is only necessary for backwards compatibility: var umbracoBaseProvider = membershipProvider as MembershipProviderBase; if (umbracoBaseProvider != null && umbracoBaseProvider.AllowManuallyChangingPassword) { //this provider allows manually changing the password without the old password, so we can just do it try { var result = umbracoBaseProvider.ChangePassword(username, "", passwordModel.NewPassword); return(result == false ? Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Could not change password, invalid username or password", new[] { "value" }) }) : Attempt.Succeed(new PasswordChangedModel())); } catch (Exception ex) { _logger.WarnWithException <PasswordChanger>("Could not change member password", ex); return(Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Could not change password, error: " + ex.Message + " (see log for full details)", new[] { "value" }) })); } } //The provider does not support manually chaning the password but no old password supplied - need to return an error if (passwordModel.OldPassword.IsNullOrWhiteSpace() && membershipProvider.EnablePasswordRetrieval == false) { //if password retrieval is not enabled but there is no old password we cannot continue return(Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Password cannot be changed without the old password", new[] { "oldPassword" }) })); } if (passwordModel.OldPassword.IsNullOrWhiteSpace() == false) { //if an old password is suplied try to change it try { var result = membershipProvider.ChangePassword(username, passwordModel.OldPassword, passwordModel.NewPassword); if (result && backofficeUserManager != null && userId >= 0) { backofficeUserManager.RaisePasswordChangedEvent(userId); } return(result == false ? Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Could not change password, invalid username or password", new[] { "oldPassword" }) }) : Attempt.Succeed(new PasswordChangedModel())); } catch (Exception ex) { _logger.WarnWithException <PasswordChanger>("Could not change member password", ex); return(Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Could not change password, error: " + ex.Message + " (see log for full details)", new[] { "value" }) })); } } if (membershipProvider.EnablePasswordRetrieval == false) { //we cannot continue if we cannot get the current password return(Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Password cannot be changed without the old password", new[] { "oldPassword" }) })); } if (membershipProvider.RequiresQuestionAndAnswer && passwordModel.Answer.IsNullOrWhiteSpace()) { //if the question answer is required but there isn't one, we cannot continue return(Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Password cannot be changed without the password answer", new[] { "value" }) })); } //lets try to get the old one so we can change it try { var oldPassword = membershipProvider.GetPassword( username, membershipProvider.RequiresQuestionAndAnswer ? passwordModel.Answer : null); try { var result = membershipProvider.ChangePassword(username, oldPassword, passwordModel.NewPassword); return(result == false ? Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Could not change password", new[] { "value" }) }) : Attempt.Succeed(new PasswordChangedModel())); } catch (Exception ex1) { _logger.WarnWithException <PasswordChanger>("Could not change member password", ex1); return(Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Could not change password, error: " + ex1.Message + " (see log for full details)", new[] { "value" }) })); } } catch (Exception ex2) { _logger.WarnWithException <PasswordChanger>("Could not retrieve member password", ex2); return(Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Could not change password, error: " + ex2.Message + " (see log for full details)", new[] { "value" }) })); } }
protected UmbracoAuthorizedJsonController(UmbracoContext umbracoContext, UmbracoHelper umbracoHelper, BackOfficeUserManager <BackOfficeIdentityUser> backOfficeUserManager) : base(umbracoContext, umbracoHelper, backOfficeUserManager) { }
public UsersController(UmbracoContext umbracoContext, UmbracoHelper umbracoHelper, BackOfficeUserManager <BackOfficeIdentityUser> backOfficeUserManager) : base(umbracoContext, umbracoHelper, backOfficeUserManager) { }
/// <summary> /// Changes password for a member/user given the membership provider and the password change model /// </summary> /// <param name="username">The username of the user having their password changed</param> /// <param name="passwordModel"></param> /// <param name="membershipProvider"></param> /// <returns></returns> public Attempt <PasswordChangedModel> ChangePasswordWithMembershipProvider(string username, ChangingPasswordModel passwordModel, MembershipProvider membershipProvider) { var umbracoBaseProvider = membershipProvider as MembershipProviderBase; // YES! It is completely insane how many options you have to take into account based on the membership provider. yikes! if (passwordModel == null) { throw new ArgumentNullException(nameof(passwordModel)); } if (membershipProvider == null) { throw new ArgumentNullException(nameof(membershipProvider)); } BackOfficeUserManager <BackOfficeIdentityUser> backofficeUserManager = null; var userId = -1; if (membershipProvider.IsUmbracoUsersProvider()) { backofficeUserManager = _httpContext.GetOwinContext().GetBackOfficeUserManager(); if (backofficeUserManager != null) { var profile = _userService.GetProfileByUserName(username); if (profile != null) { int.TryParse(profile.Id.ToString(), out userId); } } } //Are we resetting the password? //This flag indicates that either an admin user is changing another user's password without knowing the original password // or that the password needs to be reset to an auto-generated one. if (passwordModel.Reset.HasValue && passwordModel.Reset.Value) { //if a new password is supplied then it's an admin user trying to change another user's password without knowing the original password //this is only possible when using a membership provider if the membership provider supports AllowManuallyChangingPassword if (passwordModel.NewPassword.IsNullOrWhiteSpace() == false) { if (umbracoBaseProvider != null && umbracoBaseProvider.AllowManuallyChangingPassword) { //this provider allows manually changing the password without the old password, so we can just do it try { var result = umbracoBaseProvider.ChangePassword(username, string.Empty, passwordModel.NewPassword); if (result && backofficeUserManager != null && userId >= 0) { backofficeUserManager.RaisePasswordChangedEvent(userId); } return(result == false ? Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Could not change password, invalid username or password", new[] { "value" }) }) : Attempt.Succeed(new PasswordChangedModel())); } catch (Exception ex) { _logger.Warn <PasswordChanger>("Could not change member password", ex); return(Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Could not change password, error: " + ex.Message + " (see log for full details)", new[] { "value" }) })); } } else { return(Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Provider does not support manually changing passwords", new[] { "value" }) })); } } //we've made it here which means we need to generate a new password var canReset = membershipProvider.CanResetPassword(_userService); if (canReset == false) { return(Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Password reset is not enabled", new[] { "resetPassword" }) })); } if (membershipProvider.RequiresQuestionAndAnswer && passwordModel.Answer.IsNullOrWhiteSpace()) { return(Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Password reset requires a password answer", new[] { "resetPassword" }) })); } //ok, we should be able to reset it try { var newPass = membershipProvider.ResetPassword( username, membershipProvider.RequiresQuestionAndAnswer ? passwordModel.Answer : null); if (membershipProvider.IsUmbracoUsersProvider() && backofficeUserManager != null && userId >= 0) { backofficeUserManager.RaisePasswordResetEvent(userId); } //return the generated pword return(Attempt.Succeed(new PasswordChangedModel { ResetPassword = newPass })); } catch (Exception ex) { _logger.Warn <PasswordChanger>(ex, "Could not reset member password"); return(Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Could not reset password, error: " + ex.Message + " (see log for full details)", new[] { "resetPassword" }) })); } } //we're not resetting it so we need to try to change it. if (passwordModel.NewPassword.IsNullOrWhiteSpace()) { return(Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Cannot set an empty password", new[] { "value" }) })); } //without being able to retrieve the original password, //we cannot arbitrarily change the password without knowing the old one and no old password was supplied - need to return an error if (passwordModel.OldPassword.IsNullOrWhiteSpace() && membershipProvider.EnablePasswordRetrieval == false) { //if password retrieval is not enabled but there is no old password we cannot continue return(Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Password cannot be changed without the old password", new[] { "oldPassword" }) })); } if (passwordModel.OldPassword.IsNullOrWhiteSpace() == false) { //if an old password is supplied try to change it try { var result = membershipProvider.ChangePassword(username, passwordModel.OldPassword, passwordModel.NewPassword); if (result && backofficeUserManager != null && userId >= 0) { backofficeUserManager.RaisePasswordChangedEvent(userId); } return(result == false ? Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Could not change password, invalid username or password", new[] { "oldPassword" }) }) : Attempt.Succeed(new PasswordChangedModel())); } catch (Exception ex) { _logger.Warn <PasswordChanger>(ex, "Could not change member password"); return(Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Could not change password, error: " + ex.Message + " (see log for full details)", new[] { "value" }) })); } } if (membershipProvider.EnablePasswordRetrieval == false) { //we cannot continue if we cannot get the current password return(Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Password cannot be changed without the old password", new[] { "oldPassword" }) })); } if (membershipProvider.RequiresQuestionAndAnswer && passwordModel.Answer.IsNullOrWhiteSpace()) { //if the question answer is required but there isn't one, we cannot continue return(Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Password cannot be changed without the password answer", new[] { "value" }) })); } //lets try to get the old one so we can change it try { var oldPassword = membershipProvider.GetPassword( username, membershipProvider.RequiresQuestionAndAnswer ? passwordModel.Answer : null); try { var result = membershipProvider.ChangePassword(username, oldPassword, passwordModel.NewPassword); return(result == false ? Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Could not change password", new[] { "value" }) }) : Attempt.Succeed(new PasswordChangedModel())); } catch (Exception ex1) { _logger.Warn <PasswordChanger>(ex1, "Could not change member password"); return(Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Could not change password, error: " + ex1.Message + " (see log for full details)", new[] { "value" }) })); } } catch (Exception ex2) { _logger.Warn <PasswordChanger>(ex2, "Could not retrieve member password"); return(Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Could not change password, error: " + ex2.Message + " (see log for full details)", new[] { "value" }) })); } }
public TestController(UmbracoContext umbCtx, BackOfficeUserManager <BackOfficeIdentityUser> backOfficeUserManager) { _umbCtx = umbCtx; _backOfficeUserManager = backOfficeUserManager; }