public ActionResult ResetPassword(ChangePasswordInfo info) { var user = _context.Users.SingleOrDefault(x => x.ID == guid); var userChanges = user; string hash = SecurePasswordHasher.Hash(info.Password); userChanges.PasswordHash = hash; _context.Entry(user).CurrentValues.SetValues(userChanges); _context.Entry(user).State = System.Data.Entity.EntityState.Modified; _context.SaveChanges(); return(View("PasswordChanged")); }
public async Task <ActionResult> ChangePassword(ChangePasswordInfo model) { model.ReconstructSettings(); this.ViewData[ChangePasswordInfo.Key] = model; LoadPage(model.Settings.Uri); var settings = model.Settings; if (!SecurityData.IsAuthenticated) { ModelState.AddModelError("", "User is not authenticated"); } if (settings.UseValidateHuman) { bool IsValidated = model.ValidateHuman.ValidateValue(model.ValidationValue); if (!IsValidated) { ModelState.AddModelError("ValidationValue", model.ValidateHuman.AltValidationFailText); model.ValidationValue = String.Empty; } } if (ModelState.IsValid && SecurityData.IsAuthenticated) { string successView = settings.PostPartialName; if (!String.IsNullOrEmpty(settings.PostPartialName)) { successView = settings.PostPartialSuccess; } var result = await securityHelper.UserManager.ChangePasswordAsync(User.Identity.GetUserId(), model.OldPassword, model.NewPassword); if (result.Succeeded) { var user = await securityHelper.UserManager.FindByIdAsync(User.Identity.GetUserId()); if (user != null) { await securityHelper.SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); } return(PartialView(successView, model)); } AddErrors(result); } Helper.HandleErrorDict(ModelState); return(PartialView(settings.PostPartialName, model)); }
public async Task <ActionResult> ChangePassword([FromBody] ChangePassword formModel) { var changePassword = new ChangePasswordInfo { OldPassword = formModel.OldPassword, NewPassword = formModel.NewPassword, }; var result = await _userManager.ChangePasswordAsync(WorkContext.CurrentUser, formModel.OldPassword, formModel.NewPassword); return(Json(new { result.Succeeded, Errors = result.Errors.Select(x => x.Description) })); }
public async Task <IHttpActionResult> ChangePassword(string name, [FromBody] ChangePasswordInfo changePassword) { var user = await UserManager.FindByNameAsync(name); if (user == null) { return(NotFound()); } var retVal = await UserManager.ChangePasswordAsync(user.Id, changePassword.OldPassword, changePassword.NewPassword); return(Ok(retVal)); }
public bool ChangePasswordUpdateCredential(ChangePasswordInfo changepassword) { IManagerCredential crd = new ManagerCredential(); ILayoutManager layoutManager = new LayoutManager(); IManagerRole roleManager = new ManagerRole(); if (string.IsNullOrEmpty(changepassword.TenantCode) || string.IsNullOrEmpty(changepassword.UserName) || string.IsNullOrEmpty(changepassword.OldPassword) || string.IsNullOrEmpty(changepassword.NewPassword)) { return(false); } //Get tenant id with code Guid tenantId = layoutManager.GetTenantId(InfoType.Tenant, changepassword.TenantCode); if (tenantId == Guid.Empty) { return(false); } //Validate UserName var userId = crd.GetUserName(tenantId, changepassword.UserName); if (userId == Guid.Empty) { return(false); } //Validate UserName var passwordSaved = crd.GetPassword(tenantId, changepassword.UserName); if (passwordSaved == null) { return(false); } // check if password is correct if (!VerifyPasswordHash(changepassword.OldPassword, Convert.FromBase64String(passwordSaved.PasswordHash), Convert.FromBase64String(passwordSaved.PasswordSalt))) { return(false); } byte[] passwordHash, passwordSalt; CreatePasswordHash(changepassword.NewPassword, out passwordHash, out passwordSalt); CredentialInfo credentialData = crd.GetCredential(tenantId, userId); return(crd.Update(tenantId, new CredentialInfo { CredentialId = credentialData.CredentialId, ParentId = userId, UserName = changepassword.UserName, PasswordHash = Convert.ToBase64String(passwordHash), PasswordSalt = Convert.ToBase64String(passwordSalt), IsNew = false })); }
public async Task <ActionResult> ChangePassword(ChangePassword formModel) { var changePassword = new ChangePasswordInfo { OldPassword = formModel.OldPassword, NewPassword = formModel.NewPassword, }; var result = await _platformApi.Security.ChangePasswordAsync(WorkContext.CurrentCustomer.UserName, changePassword); return(Json(result)); }
public async Task <IHttpActionResult> ChangePassword(string userName, [FromBody] ChangePasswordInfo changePassword) { EnsureThatUsersEditable(userName); var result = await _securityService.ChangePasswordAsync(userName, changePassword.OldPassword, changePassword.NewPassword); if (result == null) { return(NotFound()); } return(Ok(result)); }
public static async Task ChangePasswordAsync(string tenant, int userId, ChangePasswordInfo model) { using (var db = DbProvider.Get(FrapidDbServer.GetSuperUserConnectionString(tenant), tenant).GetDatabase()) { db.BeginTransaction(); string encryptedPassword = EncryptPassword(model.Password); await db.ExecuteAsync("UPDATE account.users SET password = @0 WHERE user_id=@1;", encryptedPassword, model.UserId, encryptedPassword).ConfigureAwait(false); db.CompleteTransaction(); } }
public async Task <IActionResult> ChangePassword([FromBody] ChangePasswordInfo changePasswordInfo) { IActionResult response = BadRequest(); if (string.IsNullOrWhiteSpace(changePasswordInfo.PasswordNew) || (changePasswordInfo.PasswordNew.Length < _appSettings.MinPasswordLength)) { response = BadRequest(new ChangePasswordError { Password = new List <string> { "Invalid Password (please use at least 5 characters)." } }); } else { try { var oldPasswordHash = GetPasswordHash(changePasswordInfo.PasswordOld); var newPasswordHash = GetPasswordHash(changePasswordInfo.PasswordNew); var user = await _database.User.SingleOrDefaultAsync( u => (u.Email == HttpContext.User.Identity.Name) && (u.Password == oldPasswordHash)); if (user != null) { user.Password = newPasswordHash; await UpdateUser(user); response = NoContent(); } else { response = NotFound(new ChangePasswordError { Password = new List <string> { "Invalid password." } }); } } catch (Exception ex) { _logger.LogDebug(null, ex, "Unexpected Issue."); response = StatusCode((int)HttpStatusCode.InternalServerError); } } return(response); }
public static async Task <bool> ChangePasswordAsync(string tenant, ChangePasswordInfo model) { var user = await Users.GetAsync(tenant, model.UserId).ConfigureAwait(false); if (user == null) { return(false); } model.Email = user.Email; await Users.ChangePasswordAsync(tenant, model.UserId, model).ConfigureAwait(true); return(true); }
public ActionResult ChangePassword(ChangePasswordInfo model) { if (ModelState.IsValid) { if (UserHelper.ChangePassword(HttpContext.User.Identity.Name, model.OldPassword, model.NewPassword)) { return(Content("success")); } else { ModelState.AddModelError("", "Mật khẩu không đúng"); return(PartialView("ChangePassword", model)); } } return(PartialView("ChangePassword", model)); }
public async Task <ActionResult <PasswordChangeResult> > ChangePassword([FromBody] ChangePassword formModel) { var changePassword = new ChangePasswordInfo { OldPassword = formModel.OldPassword, NewPassword = formModel.NewPassword, }; var result = await _userManager.ChangePasswordAsync(WorkContext.CurrentUser, formModel.OldPassword, formModel.NewPassword); return(new PasswordChangeResult { Succeeded = result.Succeeded, Errors = result.Errors.Select(x => new FormError { Code = x.Code.PascalToKebabCase(), Description = x.Description }).ToList() }); }
public ActionResult ChangePassword(ChangePasswordInfo model) { if (ModelState.IsValid) { var response = ssoClientProvider.ChangePassword(model); if (response.Status == ResponseStatus.Success) { return(RedirectToAction("ChangePasswordSuccess")); } else { ViewBag.Message = response.Message; } } return(View(model)); }
public IActionResult ChangePassword([FromBody] ChangePasswordInfo changePasswordInfo) { if (!ModelState.IsValid) { throw new ApiException("Invalid input data", HttpStatusCode.BadRequest); } if (string.IsNullOrEmpty(changePasswordInfo?.Password) || string.IsNullOrEmpty(changePasswordInfo.Username)) { throw new ApiException("Invalid input data - username or password is not specified", HttpStatusCode.BadRequest); } _userManager.ChangePassword(changePasswordInfo.Username, changePasswordInfo.OldPassword, changePasswordInfo.Password); return(Ok()); }
public IServerResponse ChangePassword(ChangePasswordInfo changePasswordInfo) { Assert.IsNotNull(changePasswordInfo); Assert.IsStringNotNullOrEmpty(changePasswordInfo.OldPassword); Assert.IsStringNotNullOrEmpty(changePasswordInfo.NewPassword); Assert.AreEqual(changePasswordInfo.NewPassword, changePasswordInfo.ConfirmPassword); IServerResponse response = null; var chanel = CreateChannel(); chanel.Call(p => { response = p.ChangePassword(changePasswordInfo); }); return(response); }
public async Task <IActionResult> ChangePassword([FromBody] ChangePasswordInfo model) { ApplicationUser user = await _userManager.FindByIdAsync(model.Id); if (user == null) { return(NotFound()); } var result = await _userManager.ChangePasswordAsync(user, model.OldPassword, model.NewPassword); if (result.Succeeded) { return(Ok()); } else { return(BadRequest(result.ToString())); } }
public async Task <ActionResult> ChangePassword(ChangePassword formModel) { var changePassword = new ChangePasswordInfo { OldPassword = formModel.OldPassword, NewPassword = formModel.NewPassword, }; var result = await _platformApi.SecurityChangePasswordAsync(WorkContext.CurrentCustomer.UserName, changePassword); if (result.Succeeded == true) { return(StoreFrontRedirect("~/account")); } else { ModelState.AddModelError("form", result.Errors.First()); return(View("customers/account", WorkContext)); } }
public BooleanResult ChangePassword(ChangePasswordInfo cpInfo, ChangePasswordPluginActivityInfo pluginInfo) { m_logger.Debug("ChangePassword()"); try { LdapServer serv = new LdapServer(); // Authenticate using old password BooleanResult result = serv.Authenticate(cpInfo.Username, cpInfo.OldPassword); if (!result.Success) { return(new BooleanResult { Success = false, Message = "Password change failed: Invalid LDAP username or password." }); } // Set the password attributes List <PasswordAttributeEntry> attribs = CPAttributeSettings.Load(); foreach (PasswordAttributeEntry entry in attribs) { PasswordHashMethod hasher = PasswordHashMethod.methods[entry.Method]; m_logger.DebugFormat("Setting attribute {0} using hash method {1}", entry.Name, hasher.Name); serv.SetUserAttribute(cpInfo.Username, entry.Name, hasher.hash(cpInfo.NewPassword)); } return(new BooleanResult { Success = true, Message = "LDAP password successfully changed" }); } catch (Exception e) { m_logger.ErrorFormat("Exception in ChangePassword: {0}", e); return(new BooleanResult() { Success = false, Message = "Error in LDAP plugin." }); } }
public static ServerResponse ChangePassword(string oldPassword, string newPassword, string confirmPassword) { ServerResponse response = new ServerResponse(); if (IsAuthenticated) { ChangePasswordInfo info = new ChangePasswordInfo() { ClientId = CurrentClient.ClientId, SessionId = HttpContext.Current.Session.SessionID, DeviceId = HttpContext.Current.Request.UserHostAddress, DeviceInfo = HttpContext.Current.Request.UserAgent, UserId = CurrentSession.User.UserId, OldPassword = oldPassword, NewPassword = newPassword, ConfirmPassword = confirmPassword }; try { var cp = IocInstance.Container.Resolve <ISSOClientProvider>(); var r = cp.ChangePassword(info); response.Status = r.Status; response.Message = r.Message; } catch (Exception ex) { response.Status = ResponseStatus.Exception; response.Message = ex.Message; } } else { response.Status = ResponseStatus.Failed; response.Message = DAF.SSO.Resources.Locale(o => o.RequireAuthentication); } return(response); }
public IServerResponse ChangePassword(ChangePasswordInfo changePasswordInfo) { var client = GetClient(changePasswordInfo.ClientId); var encryptor = GetClientEncryptor(client); var hpwd = pwdEncryptor.Encrypt(changePasswordInfo.OldPassword); var obj = repoUser.Query(o => o.UserId == changePasswordInfo.UserId && o.Password == hpwd).FirstOrDefault(); ServerResponse <Session> response = new ServerResponse <Session>(); if (obj == null) { response.Status = ResponseStatus.Failed; response.Message = DAF.SSO.Resources.Locale(o => o.AccountNotFound); } else { if (changePasswordInfo.NewPassword != changePasswordInfo.ConfirmPassword) { response.Status = ResponseStatus.Failed; response.Message = DAF.SSO.Resources.Locale(o => o.ConfirmPasswordIsNotSameToPassword); } else { obj.Password = pwdEncryptor.Encrypt(changePasswordInfo.NewPassword); if (repoUser.Update(obj)) { response.Status = ResponseStatus.Success; response.Message = DAF.SSO.Resources.Locale(o => o.ChangePasswordSuccessfully); } else { response.Status = ResponseStatus.Failed; response.Message = DAF.Core.Resources.Locale(o => o.SaveFailure); } } } return(response); }
/// <summary> /// 员工修改自身密码 /// </summary> /// <param name="info">密码修改信息。</param> /// <param name="operatorAccount">操作员账号</param> /// <returns>返回修改操作是否成功。</returns> public static bool ChangePassword(ChangePasswordInfo info, string operatorAccount) { bool isSuccess = false; if (info == null) { throw new ArgumentNullException("info"); } if (info.NewPassword != info.ConfirmPassword) { throw new InvalidOperationException("\"密码\" 与 \"确认密码\" 不相同。"); } var employee = EmployeeService.QueryEmployee(info.EmployeeId); //var employee = DataContext.Employees.Where(e => e.Id == info.EmployeeId).Select(e => new Employee //{ // Id = e.Id, // Password = e.Password //}).FirstOrDefault(); if (employee == null) { throw new InvalidOperationException("指定的账号不存在。"); } if (employee.UserPassword != Utility.MD5EncryptorService.MD5FilterZero(info.OldPassword, "utf-8")) { throw new InvalidOperationException("密码不正确。"); } if (AccountBaseService.GetMebershipUser(info.UserNo)) { AccountBaseService.B3BResetLoginPassword(info.UserNo, info.NewPassword); } isSuccess = DataContext.Employees.Update(e => new { Password = Utility.MD5EncryptorService.MD5FilterZero(info.NewPassword, "utf-8") }, e => e.Id == info.EmployeeId) > 0; saveLog(OperationType.Update, "修改密码。", OperatorRole.User, info.EmployeeId.ToString(), operatorAccount); return(isSuccess); }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] ChangePasswordInfo info, ILogger log) { var table = TableUtilities.GetCloudTable("Applications"); var operation = TableOperation.Retrieve <ApplicationEntity>(info.GroupId, info.ApplicationId); var result = await table.ExecuteAsync(operation); var application = result.Result as ApplicationEntity; if (application == null) { return(new NotFoundResult()); } if (application.Password.Equals(info.Password) == false) { return(new UnauthorizedResult()); } var query = table.CreateQuery <ApplicationEntity>() .Where(p => p.PartitionKey.Equals(info.GroupId)) .AsTableQuery(); var entities = await table.ExecuteQueryAsync(query); var batch = new TableBatchOperation(); foreach (var entity in entities) { entity.Password = info.NewPassword; batch.Replace(entity); } await table.ExecuteBatchAsync(batch); return(new NoContentResult()); }
/// <summary> /// Change password /// </summary> /// <exception cref="VirtoCommerce.Platform.Client.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="userName"></param> /// <param name="changePassword">Old and new passwords.</param> /// <returns>SecurityResult</returns> public SecurityResult SecurityChangePassword(string userName, ChangePasswordInfo changePassword) { ApiResponse<SecurityResult> localVarResponse = SecurityChangePasswordWithHttpInfo(userName, changePassword); return localVarResponse.Data; }
public ActionResult ChangePassword() { ChangePasswordInfo passwordInfo = new ChangePasswordInfo(); return(View(passwordInfo)); }
/// <summary> /// Change password /// </summary> /// <exception cref="VirtoCommerce.Platform.Client.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="userName"></param> /// <param name="changePassword">Old and new passwords.</param> /// <returns>Task of ApiResponse (SecurityResult)</returns> public async System.Threading.Tasks.Task<ApiResponse<SecurityResult>> SecurityChangePasswordAsyncWithHttpInfo(string userName, ChangePasswordInfo changePassword) { // verify the required parameter 'userName' is set if (userName == null) throw new ApiException(400, "Missing required parameter 'userName' when calling VirtoCommercePlatformApi->SecurityChangePassword"); // verify the required parameter 'changePassword' is set if (changePassword == null) throw new ApiException(400, "Missing required parameter 'changePassword' when calling VirtoCommercePlatformApi->SecurityChangePassword"); var localVarPath = "/api/platform/security/users/{userName}/changepassword"; var localVarPathParams = new Dictionary<string, string>(); var localVarQueryParams = new Dictionary<string, string>(); var localVarHeaderParams = new Dictionary<string, string>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<string, string>(); var localVarFileParams = new Dictionary<string, FileParameter>(); object localVarPostBody = null; // to determine the Content-Type header string[] localVarHttpContentTypes = new string[] { "application/json", "text/json", "application/xml", "text/xml", "application/x-www-form-urlencoded" }; string localVarHttpContentType = ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header string[] localVarHttpHeaderAccepts = new string[] { "application/json", "text/json", "application/xml", "text/xml" }; string localVarHttpHeaderAccept = ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (userName != null) localVarPathParams.Add("userName", ApiClient.ParameterToString(userName)); // path parameter if (changePassword.GetType() != typeof(byte[])) { localVarPostBody = ApiClient.Serialize(changePassword); // http body (model) parameter } else { localVarPostBody = changePassword; // byte array } // make the HTTP request IRestResponse localVarResponse = (IRestResponse)await ApiClient.CallApiAsync(localVarPath, Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int)localVarResponse.StatusCode; if (localVarStatusCode >= 400 && (localVarStatusCode != 404 || Configuration.ThrowExceptionWhenStatusCodeIs404)) throw new ApiException(localVarStatusCode, "Error calling SecurityChangePassword: "******"Error calling SecurityChangePassword: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); return new ApiResponse<SecurityResult>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (SecurityResult)ApiClient.Deserialize(localVarResponse, typeof(SecurityResult))); }
public IActionResult ChangeUserPassword(ChangeUserPasswordRequest request) { if (ModelState.IsValid) { var response = new Response() { ResultCode = ResultCodes.normal }; var context = Request.HttpContext; ChangePasswordInfo changePasswordInfo = new ChangePasswordInfo(); changePasswordInfo.Password = Utils.GetSHA1Hash(request.Password); changePasswordInfo.NewPassword = Utils.GetSHA1Hash((request.NewPassword)); changePasswordInfo.RetypePassword = Utils.GetSHA1Hash((request.RetypeNewPassword)); string sessionId = ""; byte language = 0; //Սեսիայի նունականացման համար if (!string.IsNullOrEmpty(context.Request.Headers["SessionId"])) { sessionId = context.Request.Headers["SessionId"]; } //IP հասցե changePasswordInfo.IpAddress = context.Connection.RemoteIpAddress.ToString(); //Լեզու if (!string.IsNullOrEmpty(context.Request.Headers["language"])) { byte.TryParse(context.Request.Headers["language"], out language); } var changePasswordResult = _xbSecurity.ChangeUserPassword(changePasswordInfo, sessionId, language); //Եթե անցել է նույնականացում if (changePasswordResult.AuthorizationResult.IsAuthorized) { if (changePasswordResult.PasswordChangeResult.IsChanged) { response.ResultCode = ResultCodes.normal; } else { response.ResultCode = ResultCodes.failed; response.Description = changePasswordResult.PasswordChangeResult.Description; } } else { response.ResultCode = ResultCodes.failed; response.Description = changePasswordResult.AuthorizationResult.Description; } return(ResponseExtensions.ToHttpResponse(response)); } else { return(ValidationError.GetValidationErrorResponse(ModelState)); } }
public ActionResult ChangePassword() { ChangePasswordInfo model = new ChangePasswordInfo(); return(View(model)); }
public List <String> ValidatePassword(ChangePasswordInfo changepassword, PasswordPolicy passwordpolicy) { User userInfo = UserInfo(changepassword); string pass = changepassword.NewPassword; List <String> error = new List <String>(); if (userInfo != null && passwordpolicy.AllowFirstLastName != null) { if (!string.IsNullOrEmpty(userInfo.FirstName.Value) || !string.IsNullOrEmpty(userInfo.LastName.Value)) { if (passwordpolicy.AllowFirstLastName.Value) { if (pass.ToLower().Contains(userInfo.FirstName.Value.ToLower()) || pass.ToLower().Contains(userInfo.LastName.Value.ToLower())) { error.Add("validationFirstLastName"); } } } } if (passwordpolicy.IsUppercase != null) { if (passwordpolicy.IsUppercase.Value) { Regex rx = new Regex(@"(?=.*[A-Z])"); if (!rx.IsMatch(pass)) { error.Add("validationUppercase"); } } } if (passwordpolicy.IsLowercase != null) { if (passwordpolicy.IsLowercase.Value) { Regex rx = new Regex(@"(?=.*[a-z])"); if (!rx.IsMatch(pass)) { error.Add("validationLowercase"); } } } if (passwordpolicy.IsNumber != null) { if (passwordpolicy.IsNumber.Value) { Regex rx = new Regex(@"(?=.*\d)"); if (!rx.IsMatch(pass)) { error.Add("validationNumber"); } } } if (passwordpolicy.IsNonAlphaNumeric != null) { if (passwordpolicy.IsNonAlphaNumeric.Value) { Regex rx = new Regex(@"(?=.*[#$@!%&*?])"); if (!rx.IsMatch(pass)) { error.Add("validationNonAlphaNumeric"); } } } if (passwordpolicy.PasswordLength.Value != null) { // if (!Convert.ToBoolean (result.PasswordLength.Value)) { if (pass.Length < Convert.ToInt32(passwordpolicy.PasswordLength.Value.ToString())) { error.Add("validationPasswordLength"); } // } } if (passwordpolicy.PreviousPasswordDifference != null) { if (passwordpolicy.PreviousPasswordDifference.Value != "") { bool isValid = true; int count = Convert.ToInt32(passwordpolicy.PreviousPasswordDifference.Value); List <CredentialHistory> credentiallist = GetCredentialHistory(changepassword.TenantCode, changepassword.UserName, count); if (credentiallist.Count > 0) { for (int i = 0; i < credentiallist.Count; i++) { if (VerifyPasswordHash(pass, Convert.FromBase64String(credentiallist[i].PasswordHash), Convert.FromBase64String(credentiallist[i].PasswordSalt))) { isValid = false; break; } } } if (!isValid) { error.Add("validationSamePassword"); } } } return(error); }
public IServerResponse ChangePassword(ChangePasswordInfo changePasswordInfo) { return(serverProvider.ChangePassword(changePasswordInfo)); }
public ActionResult ChangePassword(ChangePasswordInfo model, int PageId) { if (model.newpassword != model.confirmnewpassword) { TempData["MessageType"] = "danger"; TempData["Message"] = "The password and Confirm password should be the same!!"; if (PageId == 1) { return(RedirectToAction("AddAdmin", model)); } else { return(RedirectToAction("Login", model)); } } if (db.Admins.Where(dbl => dbl.name.ToLower() == model.username.ToLower() && dbl.password == model.oldpassword).Count() == 1) { var AdminId = db.Admins.Where(dbl => dbl.name.ToLower() == model.username.ToLower() && dbl.password == model.oldpassword).FirstOrDefault().Id; db.Admins.Find(AdminId).password = model.newpassword; db.SaveChanges(); var fullname = db.EligibleMembers.Where(dbl => dbl.email.ToLower() == model.username.ToLower()).First().fullname; var toEmail = model.username; var EmailSubj = "Change of Your Admin Password"; var EmailMsg = "Hello " + fullname + ",\n\nYour password has been successfully changed.\n\n" + "Username: "******"\n\nPassword: "******"\n\nClick the link below to login as an admin.\n\nhttp://localhost:49296/Admin/Login"; SendEmail.Email_Without_Attachment(toEmail, EmailSubj, EmailMsg); TempData["MessageType"] = "success"; TempData["Message"] = "Your password has been successfully changed!!"; if (PageId == 1) { return(RedirectToAction("AddAdmin")); } else { return(RedirectToAction("Login")); } } if (db.Admins.Where(dbl => dbl.name.ToLower() == model.username.ToLower() && dbl.password == model.oldpassword).Count() == 0) { TempData["MessageType"] = "danger"; TempData["Message"] = "Invalid login credentials!!"; if (PageId == 1) { return(RedirectToAction("AddAdmin", model)); } else { return(RedirectToAction("Login", model)); } } else { TempData["MessageType"] = "danger"; TempData["Message"] = "Multiple login credentials for the same admin. Contact support!!"; if (PageId == 1) { return(RedirectToAction("AddAdmin", model)); } else { return(RedirectToAction("Login", model)); } } }
private ChangePasswordResponseMessage HandleChangePasswordRequest(ChangePasswordRequestMessage msg) { try { m_logger.DebugFormat("Processing ChangePasswordRequest for: {0} domain: {1}", msg.Username, msg.Domain); ChangePasswordInfo cpInfo = new ChangePasswordInfo() { Username = msg.Username, Domain = msg.Domain, OldPassword = msg.OldPassword, NewPassword = msg.NewPassword }; ChangePasswordPluginActivityInfo pluginInfo = new ChangePasswordPluginActivityInfo(); pluginInfo.LoadedPlugins = PluginLoader.GetOrderedPluginsOfType <IPluginChangePassword>(); BooleanResult finalResult = new BooleanResult { Success = false, Message = "" }; // One success means the final result is a success, and we return the message from // the last success. Otherwise, we return the message from the last failure. foreach (IPluginChangePassword plug in PluginLoader.GetOrderedPluginsOfType <IPluginChangePassword>()) { // Execute the plugin m_logger.DebugFormat("ChangePassword: executing {0}", plug.Uuid); BooleanResult pluginResult = plug.ChangePassword(cpInfo, pluginInfo); // Add result to our list of plugin results pluginInfo.AddResult(plug.Uuid, pluginResult); m_logger.DebugFormat("ChangePassword: result from {0} is {1} message: {2}", plug.Uuid, pluginResult.Success, pluginResult.Message); if (pluginResult.Success) { finalResult.Success = true; finalResult.Message = pluginResult.Message; } else { if (!finalResult.Success) { finalResult.Message = pluginResult.Message; } } } m_logger.DebugFormat("ChangePassword: returning final result {0}, message {1}", finalResult.Success, finalResult.Message); return(new ChangePasswordResponseMessage() { Result = finalResult.Success, Message = finalResult.Message, Username = msg.Username, Domain = msg.Domain }); } catch (Exception e) { m_logger.ErrorFormat("Internal error, unexpected exception while handling change password request: {0}", e); return(new ChangePasswordResponseMessage() { Result = false, Message = "Internal error" }); } }
/// <summary> /// Change password /// </summary> /// <exception cref="VirtoCommerce.Platform.Client.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="userName"></param> /// <param name="changePassword">Old and new passwords.</param> /// <returns>Task of SecurityResult</returns> public async System.Threading.Tasks.Task<SecurityResult> SecurityChangePasswordAsync(string userName, ChangePasswordInfo changePassword) { ApiResponse<SecurityResult> localVarResponse = await SecurityChangePasswordAsyncWithHttpInfo(userName, changePassword); return localVarResponse.Data; }