public async Task <UserDefinition> FindByNameAsync(string userName, CancellationToken cancellationToken) { using (UserDefinitionDataProvider dataProvider = new UserDefinitionDataProvider(this.CurrentSiteIdentity)) { UserDefinition user = await dataProvider.GetItemAsync(userName); return(user); } }
public async Task <ActionResult> UsersAdd_Partial(AddModel model) { if (!ModelState.IsValid) { return(PartialView(model)); } using (UserDefinitionDataProvider dataProvider = new UserDefinitionDataProvider()) { LoginConfigData config = await LoginConfigDataProvider.GetConfigAsync(); switch (config.RegistrationType) { default: case RegistrationTypeEnum.NameAndEmail: { // Email == model.Email List <DataProviderFilterInfo> filters = DataProviderFilterInfo.Join(null, new DataProviderFilterInfo { Field = nameof(UserDefinition.Email), Operator = "==", Value = model.Email, }); UserDefinition userExists = await dataProvider.GetItemAsync(filters); if (userExists != null) { ModelState.AddModelError(nameof(model.Email), this.__ResStr("emailUsed", "An account using email address {0} already exists.", model.Email)); return(PartialView(model)); } break; } case RegistrationTypeEnum.EmailOnly: model.UserName = model.Email; break; case RegistrationTypeEnum.NameOnly: model.UserName = model.Email; break; } UserDefinition user = model.GetData(); string hashedNewPassword; #if MVC6 IPasswordHasher <UserDefinition> passwordHasher = (IPasswordHasher <UserDefinition>)YetaWFManager.ServiceProvider.GetService(typeof(IPasswordHasher <UserDefinition>)); hashedNewPassword = passwordHasher.HashPassword(user, model.Password); #else UserManager <UserDefinition> userManager = Managers.GetUserManager(); hashedNewPassword = userManager.PasswordHasher.HashPassword(model.Password); #endif user.PasswordPlainText = config.SavePlainTextPassword ? model.Password : null; user.PasswordHash = hashedNewPassword; if (!await dataProvider.AddItemAsync(user)) { throw new Error(this.__ResStr("alreadyExists", "A user named \"{0}\" already exists."), model.UserName); } return(FormProcessed(model, this.__ResStr("okSaved", "New user saved"), OnPopupClose: OnPopupCloseEnum.ReloadModule)); } }
public async Task <int> GetUserIdAsync(string userName) { using (UserDefinitionDataProvider userDP = new UserDefinitionDataProvider()) { UserDefinition user = await userDP.GetItemAsync(userName); if (user == null) { return(0); } return(user.UserId); } }
// API // API // API /// <summary> /// Returns the user id given a login provider and key. /// </summary> /// <param name="loginProvider"></param> /// <param name="providerKey"></param> /// <returns>The UserDefinition object or null if no such user exists.</returns> public async Task <UserDefinition> GetItemAsync(string loginProvider, string providerKey) { LoginInfo info = await DataProvider.GetAsync(LoginInfo.MakeKey(loginProvider, providerKey)); if (info == null) { return(null); } using (UserDefinitionDataProvider userDP = new UserDefinitionDataProvider()) { return(await userDP.GetItemAsync(info.UserId)); } }
private async Task <UserDefinition> GetUserAsync(string userName, UserDefinitionDataProvider dataProvider) { if (string.IsNullOrWhiteSpace(userName)) { throw new Error(this.__ResStr("noItem", "No user name specified")); } UserDefinition user = await dataProvider.GetItemAsync(userName); if (user == null) { throw new Error(this.__ResStr("notFoundUser", "User {0} not found.", userName)); } return(user); }
private async Task <ExtUserInfo> GetUserInfo(LoginConfigData config) { ExtUserInfo info = new ExtUserInfo(); SignInManager <UserDefinition> _signinManager = (SignInManager <UserDefinition>)YetaWFManager.ServiceProvider.GetService(typeof(SignInManager <UserDefinition>)); ExternalLoginInfo loginInfo = await _signinManager.GetExternalLoginInfoAsync(); if (loginInfo == null) { Logging.AddErrorLog("AuthenticationManager.GetExternalLoginInfoAsync() returned null"); throw new Error(this.__ResStr("noExtLogin", "No external login has been processed")); } info.LoginInfo = loginInfo; info.Email = loginInfo.Principal.FindFirstValue(ClaimTypes.Email); info.Name = loginInfo.Principal.FindFirstValue(ClaimTypes.Name); info.LoginProvider = loginInfo.LoginProvider; info.LoginProviderDisplay = loginInfo.ProviderDisplayName; // Check whether this is an invited user using (UserDefinitionDataProvider dataProvider = new UserDefinitionDataProvider()) { List <DataProviderFilterInfo> filters = null; switch (config.RegistrationType) { default: case RegistrationTypeEnum.NameAndEmail: filters = DataProviderFilterInfo.Join(filters, new DataProviderFilterInfo { Field = nameof(UserDefinition.UserName), Operator = "==", Value = info.Name, }); filters = DataProviderFilterInfo.Join(filters, new DataProviderFilterInfo { Field = nameof(UserDefinition.Email), Operator = "==", Value = info.Email, }); break; case RegistrationTypeEnum.EmailOnly: filters = DataProviderFilterInfo.Join(filters, new DataProviderFilterInfo { Field = nameof(UserDefinition.Email), Operator = "==", Value = info.Email, }); break; case RegistrationTypeEnum.NameOnly: filters = DataProviderFilterInfo.Join(filters, new DataProviderFilterInfo { Field = nameof(UserDefinition.UserName), Operator = "==", Value = info.Name, }); break; } info.ExistingUser = await dataProvider.GetItemAsync(filters); } return(info); }
// Add a user from a site template public void AddUser(string userName) { YetaWFManager.Syncify(async() => { // rarely used so sync is OK using (UserDefinitionDataProvider dataProvider = new UserDefinitionDataProvider()) { UserDefinition user = await dataProvider.GetItemAsync(userName); if (user != null) { Users.Add(new User { UserId = user.UserId }); await SaveAsync(); } } }); }
public async Task <ActionResult> UsersEdit(string userName) { using (UserDefinitionDataProvider dataProvider = new UserDefinitionDataProvider()) { LoginConfigData config = await LoginConfigDataProvider.GetConfigAsync(); EditModel model = new EditModel { RegistrationType = config.RegistrationType, }; UserDefinition data = await dataProvider.GetItemAsync(userName); if (data == null) { throw new Error(this.__ResStr("notFound", "User \"{0}\" not found."), userName); } model.SetData(data); Module.Title = this.__ResStr("modEditTitle", "User {0}", userName); return(View(model)); } }
public async Task <ActionResult> LoginDirectDemoUser(string name, string url) { url = QueryHelper.AddRando(url ?? Manager.CurrentSite.HomePageUrl); // to defeat client-side caching using (UserDefinitionDataProvider userDP = new UserDefinitionDataProvider()) { UserDefinition user = await userDP.GetItemAsync(name); if (user == null || !user.RolesList.Contains(new Role { RoleId = Resource.ResourceAccess.GetUserDemoRoleId() }, new RoleComparer())) { Manager.CurrentResponse.StatusCode = 401; } else { await Resource.ResourceAccess.LoginAsAsync(user.UserId); } return(Redirect(url)); } }
// Change a user password private async Task ChangePasswordAsync(string userName, string newPassword) { using (UserDefinitionDataProvider dataProvider = new UserDefinitionDataProvider()) { UserDefinition user = await dataProvider.GetItemAsync(userName); if (user == null) { throw new Error(this.__ResStr("notFound", "User {0} not found", userName)); } UserManager <UserDefinition> userManager = Managers.GetUserManager(); string hashedNewPassword; #if MVC6 IPasswordHasher <UserDefinition> passwordHasher = (IPasswordHasher <UserDefinition>)YetaWFManager.ServiceProvider.GetService(typeof(IPasswordHasher <UserDefinition>)); hashedNewPassword = passwordHasher.HashPassword(user, newPassword); #else hashedNewPassword = userManager.PasswordHasher.HashPassword(newPassword); #endif //ModuleDefinition.GetPermanentGuid(typeof(RegisterModule)) LoginConfigData config = await LoginConfigDataProvider.GetConfigAsync(); user.PasswordPlainText = config.SavePlainTextPassword ? newPassword : null; user.PasswordHash = hashedNewPassword; UpdateStatusEnum status = await dataProvider.UpdateItemAsync(user); switch (status) { default: case UpdateStatusEnum.NewKeyExists: throw new InternalError("Unexpected status {0}", status); case UpdateStatusEnum.RecordDeleted: throw new Error(this.__ResStr("changeUserNotFound", "The user account for user {0} no longer exists.", userName)); case UpdateStatusEnum.OK: break; } } }
public async Task <ActionResult> ResendVerificationEmail(string userName) { using (UserDefinitionDataProvider dataProvider = new UserDefinitionDataProvider()) { if (string.IsNullOrWhiteSpace(userName)) { throw new Error(this.__ResStr("noItem", "Unable to send verification email (Reason Code 1)")); } UserDefinition user = await dataProvider.GetItemAsync(userName); if (user == null) { throw new Error(this.__ResStr("notFoundUser", "Unable to send verification email (Reason Code 2)")); } if (user.UserStatus != UserStatusEnum.NeedValidation) { throw new Error(this.__ResStr("noNeed", "Unable to send verification email (Reason Code 3)")); } Emails emails = new Emails(); await emails.SendVerificationAsync(user); return(Reload(null, Reload: ReloadEnum.ModuleParts, PopupText: this.__ResStr("verificationSent", "Verification email sent."))); } }
public async Task <ActionResult> UsersDisplay(string userName) { using (UserDefinitionDataProvider dataProvider = new UserDefinitionDataProvider()) { UserDefinition user = await dataProvider.GetItemAsync(userName); if (user == null) { throw new Error(this.__ResStr("notFound", "User \"{0}\" not found."), userName); } DisplayModel model = new DisplayModel(); model.SetData(user); using (UserLoginInfoDataProvider userLogInfoDP = new UserLoginInfoDataProvider()) { List <DataProviderFilterInfo> filters = null; filters = DataProviderFilterInfo.Join(filters, new DataProviderFilterInfo { Field = nameof(UserDefinition.UserId), Operator = "==", Value = user.UserId }); DataProviderGetRecords <LoginInfo> list = await userLogInfoDP.GetItemsAsync(0, 0, null, filters); model.LoginProviders = (from LoginInfo l in list.Data select l.LoginProvider).ToList(); } Module.Title = this.__ResStr("modDisplayTitle", "User {0}", userName); return(View(model)); } }
public async Task <ActionResult> UserAccount_Partial(EditModel model) { // make sure this user exists UserManager <UserDefinition> userManager = Managers.GetUserManager(); UserDefinition user; #if MVC6 user = await userManager.FindByNameAsync(model.OriginalUserName); #else user = userManager.FindByName(model.OriginalUserName); #endif if (user == null) { throw new Error(this.__ResStr("alreadyDeleted", "The user named \"{0}\" has been removed and can no longer be updated.", model.OriginalUserName)); } if (!ModelState.IsValid) { return(PartialView(model)); } // update email/user name - can't use an existing email address // get the registration module for some defaults LoginConfigData config = await LoginConfigDataProvider.GetConfigAsync(); switch (config.RegistrationType) { default: case RegistrationTypeEnum.NameAndEmail: { using (UserDefinitionDataProvider dataProvider = new UserDefinitionDataProvider()) { List <DataProviderFilterInfo> filters = DataProviderFilterInfo.Join(null, new DataProviderFilterInfo { Field = nameof(UserDefinition.Email), Operator = "==", Value = model.Email, }); UserDefinition userExists = await dataProvider.GetItemAsync(filters); if (userExists != null && user.UserName != userExists.UserName) { ModelState.AddModelError(nameof(model.Email), this.__ResStr("emailUsed", "An account using email address {0} already exists.", model.Email)); return(PartialView(model)); } } break; } case RegistrationTypeEnum.EmailOnly: model.UserName = model.Email; break; case RegistrationTypeEnum.NameOnly: model.Email = model.UserName; break; } // save new user info ObjectSupport.CopyData(model, user); // merge new data into original model.SetData(user); // and all the data back into model for final display if (model.OriginalUserName != user.UserName) { // user name changed - change data through data provider directly using (UserDefinitionDataProvider dataProvider = new UserDefinitionDataProvider()) { UpdateStatusEnum status = await dataProvider.UpdateItemAsync(model.OriginalUserName, user); switch (status) { default: case UpdateStatusEnum.RecordDeleted: ModelState.AddModelError(nameof(model.UserName), this.__ResStr("alreadyDeleted", "The user named \"{0}\" has been removed and can no longer be updated.", model.OriginalUserName)); return(PartialView(model)); case UpdateStatusEnum.NewKeyExists: ModelState.AddModelError(nameof(model.UserName), this.__ResStr("alreadyExists", "A user named \"{0}\" already exists.", model.UserName)); return(PartialView(model)); case UpdateStatusEnum.OK: break; } } // log the user off and back on so new name takes effect //IAuthenticationManager authManager = HttpContext.GetOwinContext().Authentication; //deleted, done in UserLogff authManager.SignOut(DefaultAuthenticationTypes.ExternalCookie, DefaultAuthenticationTypes.ApplicationCookie, DefaultAuthenticationTypes.ExternalBearer); await LoginModuleController.UserLogoffAsync(); await LoginModuleController.UserLoginAsync(user); } else { IdentityResult result; result = await userManager.UpdateAsync(user); if (!result.Succeeded) { throw new Error(string.Join(" - ", (from e in result.Errors select e.Description))); } } return(FormProcessed(model, this.__ResStr("okSaved", "Your account information has been saved"), OnClose: OnCloseEnum.ReloadPage, OnPopupClose: OnPopupCloseEnum.ReloadParentPage, ForceRedirect: true));// reload for tiny login module to refresh }
public async Task <ActionResult> Register_Partial(RegisterModel model) { LoginConfigData config = await LoginConfigDataProvider.GetConfigAsync(); if (!config.AllowUserRegistration) { throw new Error(this.__ResStr("cantRegister", "This site does not allow new user registration")); } if (model.ShowCaptcha != config.Captcha && !Manager.IsLocalHost) { throw new InternalError("Hidden field tampering detected"); } if (!model.ShowCaptcha && ModelState[nameof(model.Captcha)] != null) { ModelState[nameof(model.Captcha)].ValidationState = Microsoft.AspNetCore.Mvc.ModelBinding.ModelValidationState.Valid; } model.RegistrationType = config.RegistrationType;// don't trust what we get from user if (Module.ShowPasswordRules) { using (LoginConfigDataProvider logConfigDP = new LoginConfigDataProvider()) { model.PasswordRules = logConfigDP.PasswordRules; } } await model.UpdateAsync(); if (!ModelState.IsValid) { return(PartialView(model)); } // Create a new user and save all info UserDefinition user = new UserDefinition(); switch (config.RegistrationType) { default: case RegistrationTypeEnum.NameAndEmail: user.UserName = model.UserName; user.Email = model.Email; break; case RegistrationTypeEnum.EmailOnly: user.UserName = user.Email = model.Email; break; case RegistrationTypeEnum.NameOnly: user.UserName = user.Email = model.UserName; break; } user.PasswordPlainText = config.SavePlainTextPassword ? model.Password : null; if (config.RegistrationType == RegistrationTypeEnum.NameAndEmail) { using (UserDefinitionDataProvider dataProvider = new UserDefinitionDataProvider()) { // Email == user.Email List <DataProviderFilterInfo> filters = new List <DataProviderFilterInfo> { new DataProviderFilterInfo { Field = nameof(UserDefinition.Email), Operator = "==", Value = user.Email, }, }; UserDefinition userExists = await dataProvider.GetItemAsync(filters); if (userExists != null && user.UserName != userExists.Email) { ModelState.AddModelError(nameof(model.Email), this.__ResStr("emailUsed", "An account with email address {0} already exists.", user.Email)); return(PartialView(model)); } } } // set account status if (config.VerifyNewUsers) { user.UserStatus = UserStatusEnum.NeedValidation; } else if (config.ApproveNewUsers) { user.UserStatus = UserStatusEnum.NeedApproval; } else { user.UserStatus = UserStatusEnum.Approved; } user.RegistrationIP = Manager.UserHostAddress; // create user var result = await Managers.GetUserManager().CreateAsync(user, model.Password); if (!result.Succeeded) { foreach (var error in result.Errors) { ModelState.AddModelError(nameof(model.UserName), error.Description); ModelState.AddModelError(nameof(model.Email), error.Description); ModelState.AddModelError(nameof(model.Password), error.Description); } return(PartialView(model)); } // send appropriate email based on account status Emails emails = new Emails(); if (user.UserStatus == UserStatusEnum.NeedValidation) { await emails.SendVerificationAsync(user, config.BccVerification?Manager.CurrentSite.AdminEmail : null); string nextPage = string.IsNullOrWhiteSpace(config.VerificationPendingUrl) ? Manager.CurrentSite.HomePageUrl : config.VerificationPendingUrl; return(FormProcessed(model, this.__ResStr("okAwaitRegistration", "An email has just been sent to your email address \"{0}\" to complete the registration. Allow a few minutes for delivery. Once received, use the information in the email to complete the registration.", model.Email), this.__ResStr("okRegTitle", "Welcome!"), NextPage: nextPage)); } else if (user.UserStatus == UserStatusEnum.NeedApproval) { await emails.SendApprovalNeededAsync(user); string nextPage = string.IsNullOrWhiteSpace(config.ApprovalPendingUrl) ? Manager.CurrentSite.HomePageUrl : config.ApprovalPendingUrl; return(FormProcessed(model, this.__ResStr("okAwaitApproval", "An email has just been sent to the site administrator for approval of your new account. Once processed and approved, you will receive an email confirming your approval."), this.__ResStr("okRegTitle", "Welcome!"), NextPage: nextPage)); } else if (user.UserStatus == UserStatusEnum.Approved) { if (config.NotifyAdminNewUsers) { await emails.SendNewUserCreatedAsync(user); } await LoginModuleController.UserLoginAsync(user, config.PersistentLogin); string nextUrl = null; if (Manager.HaveReturnToUrl) { nextUrl = Manager.ReturnToUrl; } if (string.IsNullOrWhiteSpace(nextUrl) && !string.IsNullOrWhiteSpace(Module.PostRegisterUrl)) { nextUrl = Module.PostRegisterUrl; if (Module.PostRegisterQueryString) { nextUrl += model.QueryString.AddQSSeparator() + model.QueryString; } } if (string.IsNullOrWhiteSpace(nextUrl)) { nextUrl = await Resource.ResourceAccess.GetUserPostLoginUrlAsync((from u in user.RolesList select u.RoleId).ToList()); } if (string.IsNullOrWhiteSpace(nextUrl)) { nextUrl = Manager.CurrentSite.PostLoginUrl; } if (!string.IsNullOrWhiteSpace(nextUrl)) { return(FormProcessed(model, this.__ResStr("okRegText", "Your new account has been successfully registered."), this.__ResStr("okRegTitle", "Welcome!"), OnClose: OnCloseEnum.GotoNewPage, OnPopupClose: OnPopupCloseEnum.GotoNewPage, NextPage: nextUrl, ForceRedirect: true)); } return(FormProcessed(model, this.__ResStr("okRegText", "Your new account has been successfully registered."), this.__ResStr("okRegTitle", "Welcome!"), ForceRedirect: true)); } else { throw new InternalError("badUserStatus", "Unexpected account status {0}", user.UserStatus); } }
public async Task <AddUserInfo> AddUserAsync(string name, string email, string password, bool needsNewPassword, string comment) { AddUserInfo info = new AddUserInfo(); LoginConfigData config = await LoginConfigDataProvider.GetConfigAsync(); UserDefinition user = new UserDefinition { UserName = name, Email = email, PasswordPlainText = config.SavePlainTextPassword || needsNewPassword ? password : null, Comment = comment, }; if (config.RegistrationType == RegistrationTypeEnum.NameAndEmail) { using (UserDefinitionDataProvider dataProvider = new UserDefinitionDataProvider()) { // Email == user.Email List <DataProviderFilterInfo> filters = new List <DataProviderFilterInfo> { new DataProviderFilterInfo { Field = nameof(UserDefinition.Email), Operator = "==", Value = user.Email, }, }; UserDefinition userExists = await dataProvider.GetItemAsync(filters); if (userExists != null && user.UserName != userExists.Email) { info.ErrorType = AddUserInfo.ErrorTypeEnum.Email; info.Errors.Add(this.__ResStr("emailUsed", "An account with email address {0} already exists.", user.Email)); return(info); } } } user.UserStatus = UserStatusEnum.Approved; // create user var result = await Managers.GetUserManager().CreateAsync(user, password); if (!result.Succeeded) { info.ErrorType = AddUserInfo.ErrorTypeEnum.Name; foreach (var error in result.Errors) { #if MVC6 info.Errors.Add(error.Description); #else info.Errors.Add(error); #endif return(info); } } if (needsNewPassword) { using (UserDefinitionDataProvider userDP = new UserDefinitionDataProvider()) { user.NeedsNewPassword = true; if (await userDP.UpdateItemAsync(user) != UpdateStatusEnum.OK) { throw new InternalError($"Failed to update new user to set {nameof(user.NeedsNewPassword)}"); } } } info.ErrorType = AddUserInfo.ErrorTypeEnum.None; info.UserId = user.UserId; return(info); }
public async Task ResolveUserAsync() { if (!Manager.HaveCurrentRequest) { throw new InternalError("No httpRequest"); } // check whether we have a logged on user #if MVC6 if (SiteDefinition.INITIAL_INSTALL || !Manager.CurrentContext.User.Identity.IsAuthenticated) #else if (SiteDefinition.INITIAL_INSTALL || !Manager.CurrentRequest.IsAuthenticated) #endif { return;// no user logged in } // get user info and save in Manager string userName = Manager.CurrentContext.User.Identity.Name; using (UserDefinitionDataProvider userDP = new UserDefinitionDataProvider()) { if (!await userDP.IsInstalledAsync()) { Logging.AddErrorLog("UserDefinitionDataProvider not installed"); return; } UserDefinition user = await userDP.GetItemAsync(userName); if (user == null) { Logging.AddErrorLog("Authenticated user {0} doesn't exist", userName); #if DEBUG //throw new InternalError("Authenticated user doesn't exist"); #endif return; } // Check whether user needs to set up two-step authentication // External login providers don't require local two-step authentication (should be offered by external login provider) // If any of the user's roles require two-step authentication and the user has not enabled two-step authentication providers, // set marker so we can redirect the user if (Manager.Need2FAState == null) { Manager.Need2FAState = false; using (UserLoginInfoDataProvider logInfoDP = new UserLoginInfoDataProvider()) { if (!await logInfoDP.IsExternalUserAsync(user.UserId)) { // not an external login, so check if we need two-step auth LoginConfigData config = await LoginConfigDataProvider.GetConfigAsync(); if (config.TwoStepAuth != null && user.RolesList != null) { foreach (Role role in config.TwoStepAuth) { if (role.RoleId == Resource.ResourceAccess.GetUserRoleId() || user.RolesList.Contains(new Role { RoleId = role.RoleId }, new RoleComparer())) { if ((await user.GetEnabledAndAvailableTwoStepAuthenticationsAsync()).Count == 0) { Manager.Need2FAState = true; } break; } } } } } } // Check whether the user needs to change the password Manager.NeedNewPassword = user.NeedsNewPassword; // user good to go Manager.UserName = user.UserName; Manager.UserEmail = user.Email; Manager.UserId = user.UserId; Manager.UserObject = user; await UserSettings.UserSettingsAccess.ResolveUserAsync(); Manager.UserRoles = (from l in user.RolesList select l.RoleId).ToList(); int superuserRole = Resource.ResourceAccess.GetSuperuserRoleId(); if (user.RolesList.Contains(new Role { RoleId = superuserRole }, new RoleComparer())) { Manager.SetSuperUserRole(true); } } }
public async Task <ActionResult> UsersEdit_Partial(EditModel model) { using (UserDefinitionDataProvider dataProvider = new UserDefinitionDataProvider()) { string originalUserName = model.OriginalUserName; UserDefinition user = await dataProvider.GetItemAsync(originalUserName); if (user == null) { throw new Error(this.__ResStr("alreadyDeleted", "The user named \"{0}\" has been removed and can no longer be updated.", originalUserName)); } if (!ModelState.IsValid) { return(PartialView(model)); } LoginConfigData config = await LoginConfigDataProvider.GetConfigAsync(); switch (config.RegistrationType) { case RegistrationTypeEnum.NameAndEmail: { List <DataProviderFilterInfo> filters = DataProviderFilterInfo.Join(null, new DataProviderFilterInfo { Field = nameof(UserDefinition.Email), Operator = "==", Value = model.Email, }); UserDefinition userExists = await dataProvider.GetItemAsync(filters); if (userExists != null && user.UserName != userExists.UserName) { ModelState.AddModelError(nameof(model.Email), this.__ResStr("emailUsed", "An account using email address {0} already exists.", model.Email)); return(PartialView(model)); } break; } case RegistrationTypeEnum.EmailOnly: model.UserName = model.Email; break; case RegistrationTypeEnum.NameOnly: model.Email = model.UserName; break; } user = model.GetData(user); // merge new data into original model.SetData(user); // and all the data back into model for final display switch (await dataProvider.UpdateItemAsync(originalUserName, user)) { default: case UpdateStatusEnum.RecordDeleted: throw new Error(this.__ResStr("alreadyDeleted", "The user named \"{0}\" has been removed and can no longer be updated.", originalUserName)); case UpdateStatusEnum.NewKeyExists: ModelState.AddModelError(nameof(model.UserName), this.__ResStr("alreadyExists", "A user named \"{0}\" already exists.", model.UserName)); return(PartialView(model)); case UpdateStatusEnum.OK: break; } return(FormProcessed(model, this.__ResStr("okSaved", "User updated"), OnPopupClose: OnPopupCloseEnum.ReloadModule)); } }
public async Task <ActionResult> ForgotPassword_Partial(EditModel model) { LoginConfigData config = await LoginConfigDataProvider.GetConfigAsync(); if (model.ShowCaptcha != config.CaptchaForgotPassword) { throw new InternalError("Hidden field tampering detected"); } await model.UpdateAsync(); model.ShowCaptcha = config.CaptchaForgotPassword; model.RegistrationType = config.RegistrationType; if (!ModelState.IsValid) { return(PartialView(model)); } using (UserDefinitionDataProvider userDP = new UserDefinitionDataProvider()) { UserDefinition userDef; switch (model.RegistrationType) { case RegistrationTypeEnum.NameOnly: userDef = await userDP.GetItemAsync(model.UserName); if (userDef == null) { ModelState.AddModelError(nameof(model.UserName), this.__ResStr("badName", "According to our records there is no account associated with this name")); return(PartialView(model)); } break; case RegistrationTypeEnum.NameAndEmail: userDef = await userDP.GetItemAsync(model.UserNameOrEmail); if (userDef == null) { userDef = await userDP.GetItemByEmailAsync(model.UserNameOrEmail); if (userDef == null) { ModelState.AddModelError(nameof(model.UserNameOrEmail), this.__ResStr("badNameEmail", "According to our records there is no account associated with this name or email address")); return(PartialView(model)); } } break; default: case RegistrationTypeEnum.EmailOnly: userDef = await userDP.GetItemByEmailAsync(model.Email); if (userDef == null) { ModelState.AddModelError(nameof(model.Email), this.__ResStr("badEmail", "According to our records there is no account associated with this email address")); return(PartialView(model)); } break; } using (UserLoginInfoDataProvider logInfoDP = new UserLoginInfoDataProvider()) { if (await logInfoDP.IsExternalUserAsync(userDef.UserId)) { ModelState.AddModelError(nameof(model.Email), this.__ResStr("extEmail", "According to our records there is no account associated with this email address")); ModelState.AddModelError(nameof(model.UserName), this.__ResStr("extName", "According to our records there is no account associated with this name")); ModelState.AddModelError(nameof(model.UserNameOrEmail), this.__ResStr("extUser", "According to our records there is no account associated with this name or email address")); return(PartialView(model)); } } switch (userDef.UserStatus) { case UserStatusEnum.Approved: Emails emails = new Emails(); if (config.SavePlainTextPassword) { await emails.SendForgottenEmailAsync(userDef, config.BccForgottenPassword?Manager.CurrentSite.AdminEmail : null); string from = emails.GetSendingEmailAddress(); return(FormProcessed(model, this.__ResStr("okForgot", "We just sent an email to your email address with your password information - Please allow a few minutes for delivery and make sure your spam filters allow emails from {0}", from), OnClose: OnCloseEnum.Nothing, OnPopupClose: OnPopupCloseEnum.ReloadModule)); } else { if (userDef.ResetKey != null && userDef.ResetValidUntil != null && userDef.ResetValidUntil > DateTime.UtcNow) { // preserve existing key in case user resends } else { userDef.ResetKey = Guid.NewGuid(); userDef.ResetValidUntil = DateTime.UtcNow.Add(config.ResetTimeSpan); if (await userDP.UpdateItemAsync(userDef) != Core.DataProvider.UpdateStatusEnum.OK) // update reset key info { throw new Error(this.__ResStr("resetUpdate", "User information could not be updated")); } } await emails.SendPasswordResetEmailAsync(userDef, config.BccForgottenPassword?Manager.CurrentSite.AdminEmail : null); string from = emails.GetSendingEmailAddress(); return(FormProcessed(model, this.__ResStr("okReset", "We just sent an email to your email address to reset your password - Please allow a few minutes for delivery and make sure your spam filters allow emails from {0}", from), OnClose: OnCloseEnum.Nothing, OnPopupClose: OnPopupCloseEnum.ReloadModule)); } case UserStatusEnum.NeedApproval: throw new Error(this.__ResStr("needApproval", "This account has not yet been approved and is awaiting approval by the site administrator")); case UserStatusEnum.NeedValidation: throw new Error(this.__ResStr("needValidation", "This account has not yet been verified - Please check your emails for our verification email")); case UserStatusEnum.Rejected: throw new Error(this.__ResStr("rejected", "This account has been rejected and is not accessible")); case UserStatusEnum.Suspended: throw new Error(this.__ResStr("suspended", "This account has been suspended and is not accessible")); default: throw new Error(this.__ResStr("unknownState", "This account is in an undefined state and is not accessible")); } } }