public async Task Can_signup_user_and_change_password() { // Arrange var authenticationApiClient = new AuthenticationApiClient(new Uri(GetVariable("AUTH0_AUTHENTICATION_API_URL"))); // Sign up the user var signupUserRequest = new SignupUserRequest { ClientId = clientId, Connection = connection.Name, Email = $"{Guid.NewGuid().ToString("N")}@nonexistingdomain.aaa", Password = "******" }; var signupUserResponse = await authenticationApiClient.SignupUserAsync(signupUserRequest); signupUserResponse.Should().NotBeNull(); signupUserResponse.Email.Should().Be(signupUserRequest.Email); // Change the user's Email address var changePasswordRequest = new ChangePasswordRequest { ClientId = signupUserRequest.ClientId, Connection = signupUserRequest.Connection, Email = signupUserRequest.Email, Password = "******" }; string changePasswordResponse = await authenticationApiClient.ChangePasswordAsync(changePasswordRequest); changePasswordResponse.Should().Be("\"We've just sent you an Email to reset your password.\""); }
public Result<ServiceResponse> ChangePassword(ChangePasswordRequest request) { return this.InTransaction("Default", uow => { request.CheckNotNull(); if (string.IsNullOrEmpty(request.OldPassword)) throw new ArgumentNullException("oldPassword"); var username = Authorization.Username; if (!Dependency.Resolve<IAuthenticationService>().Validate(ref username, request.OldPassword)) throw new ValidationError("CurrentPasswordMismatch", Texts.Validation.CurrentPasswordMismatch); if (request.ConfirmPassword != request.NewPassword) throw new ValidationError("PasswordConfirmMismatch", LocalText.Get("Validation.PasswordConfirm")); request.NewPassword = UserRepository.ValidatePassword(username, request.NewPassword, false); var salt = Membership.GeneratePassword(5, 1); var hash = SiteMembershipProvider.ComputeSHA512(request.NewPassword + salt); uow.Connection.UpdateById(new UserRow { UserId = int.Parse(Authorization.UserId), PasswordSalt = salt, PasswordHash = hash }); BatchGenerationUpdater.OnCommit(uow, UserRow.Fields.GenerationKey); return new ServiceResponse(); }); }
public Response ChangePassword(ChangePasswordRequest request) { var user = MonospadContext.Current.User; var login = MonospadContext.Current.Login; user.Password = _crypto.ComputeHash(request.NewPassword); _repository.Update(user); login.ExpireDate = DateTime.UtcNow; _repository.Update(login); login = CreateLogin(user); return Response.Success.WithData(new { login.Token }); }
public bool ChangePassword(ChangePasswordRequest request) { string authenticationToken = FetchAuthenticationTokenFromRequest(); return ChangePassword(authenticationToken, request.OldPassword, request.NewPassword); }
public ActionResult TaoTaiKhoan(XuLyHopDongModel.KhachHangModel model) { if (!_permissionService.Authorize(StandardPermissionProvider.CVLeTanHopDong)) { return(AccessDeniedView()); } var khachhangrole = new CustomerRole(); var customer = new Customer { CustomerGuid = Guid.NewGuid(), Email = model.Email, Active = true, CreatedOnUtc = DateTime.UtcNow, LastActivityDateUtc = DateTime.UtcNow, }; var item = _customerService.GetCustomerByEmail(model.Email); if (item == null) { _customerService.InsertCustomer(customer); //firstname,lastname _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.FirstName, model.FirstName); _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.LastName, model.LastName); //mã hóa password if (!String.IsNullOrWhiteSpace(model.Password)) { var changePassRequest = new ChangePasswordRequest(model.Email, false, _customerSettings.DefaultPasswordFormat, model.Password); var changePassResult = _customerRegistrationService.ChangePassword(changePassRequest); if (!changePassResult.Success) { foreach (var changePassError in changePassResult.Errors) { ErrorNotification(changePassError); } } } //update khách hàng cho hop dong var _hopdong = _chonveService.GetHopDongById(model.HopDongId); if (_hopdong != null) { if (_hopdong.KhachHangID > 0 && _hopdong.KhachHangID != customer.Id) { var khachhang = _customerService.GetCustomerById(_hopdong.KhachHangID); var newitemrole = new CustomerRole(); foreach (var _item in khachhang.CustomerRoles) { if (_item.SystemName == SystemCustomerRoleNames.HTNhaXeManager) { newitemrole = _item; } } khachhang.CustomerRoles.Remove(newitemrole); _customerService.UpdateCustomer(khachhang); } _hopdong.KhachHangID = customer.Id; _chonveService.UpdateHopDong(_hopdong); } //customerrole var allCustomerRoles = _customerService.GetAllCustomerRoles(true); var newCustomerRoles = new List <CustomerRole>(); foreach (var customerRole in allCustomerRoles) { if (customerRole.SystemName == SystemCustomerRoleNames.Registered) { newCustomerRoles.Add(customerRole); } if (customerRole.SystemName == SystemCustomerRoleNames.HTNhaXeManager) { newCustomerRoles.Add(customerRole); } } foreach (var _customerRole in newCustomerRoles) { customer.CustomerRoles.Add(_customerRole); } _customerService.UpdateCustomer(customer); //tạo văn phong với địa chỉ của nhà xe là trụ sở chính var truso = new VanPhong(); truso.NhaXeId = _hopdong.NhaXeID; var nhaxe = _nhaxeService.GetNhaXeById(_hopdong.NhaXeID); truso.TenVanPhong = nhaxe.TenNhaXe; truso.KieuVanPhongID = (int)ENKieuVanPhong.TruSo; truso.DiaChiID = nhaxe.DiaChiID; _nhaxeService.InsertVanPhong(truso); // tao nhan vien thuoc van phong var nhanvien = new NhanVien(); nhanvien.HoVaTen = nhaxe.TenNhaXe; nhanvien.Email = nhaxe.Email; nhanvien.CustomerID = customer.Id; nhanvien.KieuNhanVienID = (int)ENKieuNhanVien.QuanLy; nhanvien.GioiTinhID = (int)ENGioiTinh.Nam; nhanvien.TrangThaiID = (int)ENTrangThaiNhanVien.DangLamViec; nhanvien.NgayBatDauLamViec = DateTime.Now; nhanvien.VanPhongID = truso.Id; nhanvien.NhaXeID = _hopdong.NhaXeID; nhanvien.DiaChiID = nhaxe.DiaChiID; _nhanvienService.Insert(nhanvien); return(RedirectToAction("ChiTietHopDong", new { id = model.HopDongId })); } return(View()); }
/// <summary> /// After the Record has been saved /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="R"></typeparam> /// <typeparam name="S"></typeparam> /// <param name="request"></param> /// <param name="originalRecord"></param> /// <param name="record"></param> /// <returns></returns> public override bool PostSave <T, R, S>(S request, T originalRecord, T record, R response) { var saveRequest = request as SecurityUserMaintenanceSaveRequest; var saveResponse = response as SecurityUserMaintenanceSaveResponse; var securityUser = record as SecurityUser; // //Change the users password if a new password was submitted // if (!String.IsNullOrWhiteSpace(saveRequest.NewPassword) || !String.IsNullOrWhiteSpace(saveRequest.NewPasswordConfirm)) { var changePasswordRequest = new ChangePasswordRequest() { UserName = securityUser.UserName, AuthenticationMethod = securityUser.AuthenticationMethod, SecurityUserId = securityUser.SecurityUserId, NewPassword = saveRequest.NewPassword, NewPasswordConfirm = saveRequest.NewPasswordConfirm, CheckPasswordComplexity = false, CheckIfUserPasswordCanBeChanged = false, EnforcePasswordHistory = false, SendPasswordSuccessfullyChangedEmail = false }; var changePasswordResponse = _passwordService.ChangePassword(changePasswordRequest); if (!changePasswordResponse.IsSuccessful) { response.IsSuccessful = false; response.Message = "An error occurred setting the users password. " + changePasswordResponse.Message; } } // //Assign the roles to the user submitted in the save request // if (saveRequest.AssignedRoleIds != null) { var assignedRoles = _repository.GetAll <SecurityUserRoleMembership>(p => p.User, p => p.Role) .Where(p => p.SecurityUserId == securityUser.SecurityUserId && p.Role.Active == true) .ToList(); // //Remove any roles currently assigned to the user that were not submitted in the list //of AssignedRoleIds (the list of roles the user should have) // foreach (var assignedRole in assignedRoles) { if (!saveRequest.AssignedRoleIds.Contains(assignedRole.SecurityRoleId)) { _repository.Delete(assignedRole); } } // //Add any new roles to the user not yet assigned. The roles submitted in the list //of AssignedRoleIds are the current roles the user should have. // foreach (var assignedRoleId in saveRequest.AssignedRoleIds) { if (assignedRoles.FirstOrDefault(p => p.SecurityRoleId == assignedRoleId) == null) { var securityUserRoleMembership = new SecurityUserRoleMembership() { SecurityRoleId = assignedRoleId, SecurityUserId = securityUser.SecurityUserId, Active = true }; _repository.Add(securityUserRoleMembership); } } } _repository.Commit(); // //Get the roles available for and assigned to the user. // var rolesForUserRequest = new SecurityUserMaintenanceGetRolesForUserRequest() { SecurityUserId = securityUser.SecurityUserId }; var rolesForUserResponse = GetRolesForUser(rolesForUserRequest); saveResponse.AvailableRoles = rolesForUserResponse.AvailableRoles; saveResponse.AssignedRoles = rolesForUserResponse.AssignedRoles; //Dont need the caller to commit after this processing is done return(false); }
private async void ChangePassword() { if (string.IsNullOrEmpty(CurrentPassword)) { await dialogService.ShowMessage("Error", "You must enter the current password."); return; } var mainViewModel = MainViewModel.GetInstance(); if (mainViewModel.CurrentUser.Password != CurrentPassword) { await dialogService.ShowMessage("Error", "the current password does not match"); return; } if (string.IsNullOrEmpty(NewPassword)) { await dialogService.ShowMessage("Error", "You must enter the current password."); return; } if (NewPassword == CurrentPassword) { await dialogService.ShowMessage("Error", "the current password is the same than current password"); return; } if (string.IsNullOrEmpty(ConfirmPassword)) { await dialogService.ShowMessage("Error", "You must enter the current password."); return; } if (NewPassword.Length < 6) { await dialogService.ShowMessage("Error", "The new password must have at least 6 characters."); return; } if (string.IsNullOrEmpty(ConfirmPassword)) { await dialogService.ShowMessage("Error", "You must enter a password confirm."); return; } if (NewPassword != ConfirmPassword) { await dialogService.ShowMessage("Error", "The new password and confirm does not match."); return; } IsRunning = true; IsEnabled = false; var parameters = dataService.First <Parameter>(false); var user = dataService.First <User>(false); var request = new ChangePasswordRequest { CurrentPassword = CurrentPassword, Email = user.Email, NewPassword = NewPassword }; var response = await apiService.ChangePassword(parameters.UrlBase, "/api", "/Users/ChangePassword", user.TokenType, user.AccessToken, request); IsRunning = false; IsEnabled = true; if (!response.IsSuccess) { await dialogService.ShowMessage("Error", response.Message); return; } await dialogService.ShowMessage("Confirm", "Your Password has been changed successfully"); await navigationService.Back(); }
public JsonMessage ChangePassword(ChangePasswordRequest input) { return null; }
public async Task <HttpOperationResponse <object> > PostChangePasswordWithHttpMessagesAsync(ChangePasswordRequest changePasswordRequest, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (changePasswordRequest == null) { throw new ValidationException(ValidationRules.CannotBeNull, "changePasswordRequest"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("changePasswordRequest", changePasswordRequest); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PostChangePassword", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/account/changepassword").ToString(); // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if (changePasswordRequest != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(changePasswordRequest, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse <object>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <object>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
/// <summary> /// Initiates the asynchronous execution of the ChangePassword operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ChangePassword operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<ChangePasswordResponse> ChangePasswordAsync(ChangePasswordRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new ChangePasswordRequestMarshaller(); var unmarshaller = ChangePasswordResponseUnmarshaller.Instance; return InvokeAsync<ChangePasswordRequest,ChangePasswordResponse>(request, marshaller, unmarshaller, cancellationToken); }
public async Task <ToRespond> ChangePassword(ChangePasswordRequest changePasswordRequest) { if (changePasswordRequest == null || string.IsNullOrWhiteSpace(changePasswordRequest.OldPassword) || string.IsNullOrWhiteSpace(changePasswordRequest.NewPassword)) { return(new ToRespond() { StatusCode = Helpers.ObjectNull, StatusMessage = Helpers.StatusMessageObjectNull }); } if (changePasswordRequest.OldPassword == changePasswordRequest.NewPassword) { return(new ToRespond() { StatusCode = Helpers.PreviousPasswordStorageError, StatusMessage = "Previous Password Is Same As New Password" }); } var loggedInUser = _globalRepository.GetUserInformation(); var user = await _userManager.FindByIdAsync(loggedInUser.UserId); var dbTransaction = await _dataContext.Database.BeginTransactionAsync(); if (user != null) { var newPasswordHash = _userManager.PasswordHasher.HashPassword(user, changePasswordRequest.NewPassword); if (user.PasswordHash.Equals(newPasswordHash)) { await dbTransaction.RollbackAsync(); return(new ToRespond() { StatusCode = Helpers.NewPasswordError, StatusMessage = "New Password error" }); } var result = await _userManager.ChangePasswordAsync(user, changePasswordRequest.OldPassword, changePasswordRequest.NewPassword); if (result.Succeeded) { await dbTransaction.CommitAsync(); return(new ToRespond() { StatusCode = Helpers.Success, StatusMessage = "Password Changed Successfully", ObjectValue = user }); } else { return(new ToRespond() { StatusCode = Helpers.SaveError, StatusMessage = Helpers.StatusMessageSaveError }); } } else { await dbTransaction.RollbackAsync(); return(new ToRespond() { StatusCode = Helpers.NotFound, StatusMessage = Helpers.StatusMessageNotFound }); } }
public async Task <Response> ChangePassword(string urlBase, string servicePrefix, string controller, string tokenType, string accessToken, ChangePasswordRequest changePasswordRequest) { try { var request = JsonConvert.SerializeObject(changePasswordRequest); var content = new StringContent(request, Encoding.UTF8, "application/json"); var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(tokenType, accessToken); client.BaseAddress = new Uri(urlBase); var url = string.Format("{0}{1}", servicePrefix, controller); var response = await client.PostAsync(url, content); if (!response.IsSuccessStatusCode) { return(new Response { IsSuccess = false, Message = response.StatusCode.ToString(), }); } return(new Response { IsSuccess = true, Message = "Record added OK", Result = "Password Changed Success", }); } catch (Exception ex) { return(new Response { IsSuccess = false, Message = ex.Message, }); } }
public void ChangePasswordAsync(ChangePasswordRequest request, Action <ResponseBase, Exception> callback) { RpcRoot.SignPostAsync(RpcRoot.OfficialServerHost, RpcRoot.OfficialServerPort, _controllerName, nameof(IUserController.ChangePassword), request, callback); }
async void Save() { if (string.IsNullOrEmpty(CurrentPassword)) { await dialogService.ShowMessage( "Error", "You must enter the current password."); return; } var mainViewModel = MainViewModel.GetInstance(); if (!mainViewModel.Token.Password.Equals(CurrentPassword)) { await dialogService.ShowMessage( "Error", "The current password is not valid"); return; } if (string.IsNullOrEmpty(NewPassword)) { await dialogService.ShowMessage( "Error", "You must enter a new password."); return; } if (NewPassword.Length < 6) { await dialogService.ShowMessage( "Error", "The new password must have at least 6 characters length."); return; } if (string.IsNullOrEmpty(ConfirmPassword)) { await dialogService.ShowMessage( "Error", "You must enter a new password confirm."); return; } if (!NewPassword.Equals(ConfirmPassword)) { await dialogService.ShowMessage( "Error", "The new password and confirm, does not match."); return; } IsRunning = true; IsEnabled = false; var connection = await apiService.CheckConnection(); if (!connection.IsSuccess) { IsRunning = false; IsEnabled = true; await dialogService.ShowMessage("Error", connection.Message); return; } var changePasswordRequest = new ChangePasswordRequest { CurrentPassword = CurrentPassword, Email = mainViewModel.Token.UserName, NewPassword = NewPassword, }; var urlAPI = Application.Current.Resources["URLAPI"].ToString(); var response = await apiService.ChangePassword( urlAPI, "/api", "/Customers/ChangePassword", mainViewModel.Token.TokenType, mainViewModel.Token.AccessToken, changePasswordRequest); if (!response.IsSuccess) { IsRunning = false; IsEnabled = true; await dialogService.ShowMessage( "Error", response.Message); return; } mainViewModel.Token.Password = NewPassword; dataService.Update(mainViewModel.Token); await dialogService.ShowMessage( "Confirm", "The password was changed successfully"); await navigationService.BackOnMaster(); IsRunning = false; IsEnabled = true; }
Task<ChangePasswordResponse> IManageOrders.ChangePasswordAsync(ChangePasswordRequest request) { throw new NotImplementedException(); }
/// <summary> /// Change Password for an existing user. /// </summary> /// <param name="request">Instance of ChangePasswordRequest</param> /// <returns>Instance of ChangePasswordResponse</returns> public async Task<ChangePasswordResponse> ChangePasswordAsync(ChangePasswordRequest request) { ChangePasswordResponse response = new ChangePasswordResponse(); try { IdentityResult result = await UserManager.ChangePasswordAsync(request.UserId.ToString(), request.OldPassword, request.NewPassword); if (!result.Succeeded) { foreach (string item in response.Errors) response.Errors.Add(item); response.Success = false; } else { response.Success = true; } } catch (Exception e) { response.Success = false; response.Errors.Add(e.Message); } return response; }
/// <summary> /// Allows an authenticated user to change their password using an /// asynchronous call /// </summary> /// <param name="oldPass">The user's old password</param> /// <param name="newPass">The desired new password</param> public Task ChangePasswordAsync(string oldPass, string newPass) { ChangePasswordRequest changePassRequest = CreateChangePasswordRequest(oldPass, newPass); return(Provider.ChangePasswordAsync(changePassRequest)); }
public async Task <IActionResult> ChangePassword(ChangePasswordRequest request, [FromServices] IHandler <ChangePasswordRequest, ObjectResult> handler) { return(await handler.Handle(request)); }
/// <summary> /// Given the user's details, Auth0 will send a forgot password email. /// </summary> /// <param name="request">The <see cref="ChangePasswordRequest" /> specifying the user and connection details.</param> /// <returns>A string containing the message returned from Auth0.</returns> public Task <string> ChangePasswordAsync(ChangePasswordRequest request) { return(Connection.PostAsync <string>("dbconnections/change_password", request, null, null, null, null, null)); }
public bool ForgotChangePassword(ChangePasswordRequest request) { var response = new TransactionInfoResponse(); try { IHttpOrderClient client = new HttpOrderClient(Publickey, true); var dic = new Dictionary<string, string>(); var url = GetUrl(BusinessObjectPublicUser.RequestFunction.ForgotChangePassword); var result = client.Post(request, url, dic, Appid, Uid); if (result != null && result.ResponseData != null) { ResponseMessage = result.Message; Status = result.Status; return SerializerObject.ProtoBufDeserialize<bool>(result.ResponseData, client.Saltkey); } return false; } catch (Exception exception) { ResponseMessage = "User API - " + SetResponseMessage(exception); return false; } }
public NegotiatedContentResult <ResponseDto> PostChangePassword([FromBody] ChangePasswordRequest request) { ResponseDto resp = _userServices.ChangePassword(request); return(Content(HttpStatusCode.OK, resp)); }
public Task<string> ChangePassword(ChangePasswordRequest request) { return Connection.PostAsync<string>("dbconnections/change_password", request, null, null, null, null, null); }
public static async Task <ChangePasswordResponse> ChangePasswordApi(ChangePasswordRequest request) { return(await CustomHttpClient.Post <ChangePasswordResponse>(request, "/UpdateLoginInformation")); }
private void button3_Click(object sender, EventArgs e) { ChangePasswordRequest request = new ChangePasswordRequest(); request.token = token; request.form = new Form.ChangePasswordUpdateForm { UserID = "1", NewPassword = "******", }; var res = SDKFactory.Client.Execute(request); MessageBox.Show(res.ResponseBody); }
public async Task <ActionResult> ChangePassword(ChangePasswordRequest model) => await this.identityService.ChangePassword(model);
public async Task <Response> ChangePasswordAsync(string urlBase, string servicePrefix, string controller, ChangePasswordRequest changePasswordRequest, string tokenType, string accessToken) { try { string request = JsonConvert.SerializeObject(changePasswordRequest); StringContent content = new StringContent(request, Encoding.UTF8, "application/json"); HttpClient client = new HttpClient { BaseAddress = new Uri(urlBase) }; client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(tokenType, accessToken); string url = $"{servicePrefix}{controller}"; HttpResponseMessage response = await client.PostAsync(url, content); string answer = await response.Content.ReadAsStringAsync(); Response obj = JsonConvert.DeserializeObject <Response>(answer); return(obj); } catch (Exception ex) { return(new Response { IsSuccess = false, Message = ex.Message, }); } }
public async Task <IResult> ChangePasswordAsync(ChangePasswordRequest model) { var response = await _httpClient.PutAsJsonAsync(Routes.AccountEndpoints.ChangePassword, model); return(await response.ToResult()); }
public Task <string> ChangePasswordAsync(ChangePasswordRequest request) { return(_inner.ChangePasswordAsync(request)); }
public ChangePasswordResponse ChangePassword(ChangePasswordRequest request) { ChangePasswordResponse response = new ChangePasswordResponse(); AuthToken authToken = null; try { Common.Helpers.ValidationHelper.ValidateRequiredField(request.AuthToken, "Auth Token"); Common.Helpers.ValidationHelper.ValidateRequiredField(request.AntiForgeryToken, "Anti Forgery Token"); Common.Helpers.ValidationHelper.ValidateRequiredField(request.OldPassword, "Old Password"); Common.Helpers.ValidationHelper.ValidateRequiredField(request.NewPassword, "New Password"); Common.Helpers.ValidationHelper.ValidateStringLength(request.OldPassword, "Old Password", Constants.MaxPasswordLength); Common.Helpers.ValidationHelper.ValidateStringLength(request.NewPassword, "New Password", Constants.MaxPasswordLength); Common.Helpers.ValidationHelper.AssertFalse(request.NewPassword.Equals(request.OldPassword), "New Password and old password are equal."); if (!UserController.ValidateSession(request.AuthToken, out authToken)) { throw new AuthenticationException("Authentication failed."); } UserController.ValidateAntiForgeryToken(request.AntiForgeryToken, authToken); ValidationHelper.ValidatePassword(request.NewPassword); UserController.ChangePassword(authToken.Username, request.OldPassword, request.NewPassword); } catch (AuthenticationException ex) { throw new WebFaultException<string>(ex.Message, System.Net.HttpStatusCode.Unauthorized); } catch (Common.Exceptions.ValidationException ex) { throw new WebFaultException<string>(ex.Message, System.Net.HttpStatusCode.Unauthorized); } catch (Exception ex) { ExceptionHelper.Log(ex, authToken == null ? null : authToken.Username); throw new WebFaultException<string>("An unknown error has occurred.", System.Net.HttpStatusCode.InternalServerError); } return response; }
private async void ChangePassword() { if (string.IsNullOrEmpty(this.CurrentPassword)) { await Application.Current.MainPage.DisplayAlert( Languages.Error, Languages.PasswordValidation, Languages.Accept); return; } if (this.CurrentPassword.Length < 6) { await Application.Current.MainPage.DisplayAlert( Languages.Error, Languages.PasswordValidation2, Languages.Accept); return; } if (this.CurrentPassword != MainViewModel.GetInstance().User.Password) { await Application.Current.MainPage.DisplayAlert( Languages.Error, Languages.PasswordError, Languages.Accept); return; } if (string.IsNullOrEmpty(this.NewPassword)) { await Application.Current.MainPage.DisplayAlert( Languages.Error, Languages.PasswordValidation, Languages.Accept); return; } if (this.NewPassword.Length < 6) { await Application.Current.MainPage.DisplayAlert( Languages.Error, Languages.PasswordValidation2, Languages.Accept); return; } if (string.IsNullOrEmpty(this.Confirm)) { await Application.Current.MainPage.DisplayAlert( Languages.Error, Languages.ConfirmValidation, Languages.Accept); return; } if (this.NewPassword != this.Confirm) { await Application.Current.MainPage.DisplayAlert( Languages.Error, Languages.ConfirmValidation2, Languages.Accept); return; } this.IsRunning = true; this.IsEnabled = false; var connection = await this.apiService.CheckConnection(); if (!connection.IsSuccess) { this.IsRunning = false; this.IsEnabled = true; await Application.Current.MainPage.DisplayAlert( Languages.Error, connection.Message, Languages.Accept); return; } var request = new ChangePasswordRequest { CurrentPassword = this.CurrentPassword, Email = MainViewModel.GetInstance().User.Email, NewPassword = this.NewPassword, }; var apiSecurity = Application.Current.Resources["APISecurity"].ToString(); var response = await this.apiService.ChangePassword( apiSecurity, "/api", "/Users/ChangePassword", MainViewModel.GetInstance().Token.TokenType, MainViewModel.GetInstance().Token.AccessToken, request); if (!response.IsSuccess) { this.IsRunning = false; this.IsEnabled = true; await Application.Current.MainPage.DisplayAlert( Languages.Error, Languages.ErrorChangingPassword, Languages.Accept); return; } MainViewModel.GetInstance().User.Password = this.NewPassword; this.dataService.Update(MainViewModel.GetInstance().User); this.IsRunning = false; this.IsEnabled = true; await Application.Current.MainPage.DisplayAlert( Languages.ConfirmLabel, Languages.ChagePasswordConfirm, Languages.Accept); await App.Navigator.PopAsync(); }
/// <summary> /// Change password /// </summary> /// <param name="request">Request</param> /// <returns>Result</returns> public virtual ChangePasswordResult ChangePassword(ChangePasswordRequest request) { if (request == null) throw new ArgumentNullException("request"); var result = new ChangePasswordResult(); if (String.IsNullOrWhiteSpace(request.Email)) { result.AddError(_localizationService.GetResource("Account.ChangePassword.Errors.EmailIsNotProvided")); return result; } if (String.IsNullOrWhiteSpace(request.NewPassword)) { result.AddError(_localizationService.GetResource("Account.ChangePassword.Errors.PasswordIsNotProvided")); return result; } var user = _userService.GetUserByEmail(request.Email); if (user == null) { result.AddError(_localizationService.GetResource("Account.ChangePassword.Errors.EmailNotFound")); return result; } var requestIsValid = false; if (request.ValidateRequest) { //password string oldPwd = ""; switch (user.PasswordFormat) { case PasswordFormat.Encrypted: oldPwd = _encryptionService.EncryptText(request.OldPassword); break; case PasswordFormat.Hashed: oldPwd = _encryptionService.CreatePasswordHash(request.OldPassword, user.PasswordSalt, _userSettings.HashedPasswordFormat); break; default: oldPwd = request.OldPassword; break; } bool oldPasswordIsValid = oldPwd == user.Password; if (!oldPasswordIsValid) result.AddError(_localizationService.GetResource("Account.ChangePassword.Errors.OldPasswordDoesntMatch")); if (oldPasswordIsValid) requestIsValid = true; } else requestIsValid = true; //at this point request is valid if (requestIsValid) { switch (request.NewPasswordFormat) { case PasswordFormat.Clear: { user.Password = request.NewPassword; } break; case PasswordFormat.Encrypted: { user.Password = _encryptionService.EncryptText(request.NewPassword); } break; case PasswordFormat.Hashed: { string saltKey = _encryptionService.CreateSaltKey(5); user.PasswordSalt = saltKey; user.Password = _encryptionService.CreatePasswordHash(request.NewPassword, saltKey, _userSettings.HashedPasswordFormat); } break; default: break; } user.PasswordFormat = request.NewPasswordFormat; _userService.UpdateUser(user); } return result; }
public async Task <IActionResult> Create(CustomerModel model, bool continueEditing, IFormCollection form) { if (!string.IsNullOrWhiteSpace(model.Email)) { var cust2 = await _customerService.GetCustomerByEmail(model.Email); if (cust2 != null) { ModelState.AddModelError("", "Email is already registered"); } } if (!string.IsNullOrWhiteSpace(model.Username) & _customerSettings.UsernamesEnabled) { var cust2 = await _customerService.GetCustomerByUsername(model.Username); if (cust2 != null) { ModelState.AddModelError("", "Username is already registered"); } } //validate customer roles var allCustomerRoles = await _customerService.GetAllCustomerRoles(true); var newCustomerRoles = new List <CustomerRole>(); foreach (var customerRole in allCustomerRoles) { if (model.SelectedCustomerRoleIds != null && model.SelectedCustomerRoleIds.Contains(customerRole.Id)) { newCustomerRoles.Add(customerRole); } } var customerRolesError = _customerViewModelService.ValidateCustomerRoles(newCustomerRoles); if (!string.IsNullOrEmpty(customerRolesError)) { ModelState.AddModelError("", customerRolesError); ErrorNotification(customerRolesError, false); } if (ModelState.IsValid) { model.CustomAttributes = await ParseCustomCustomerAttributes(form); var customer = await _customerViewModelService.InsertCustomerModel(model); //password if (!string.IsNullOrWhiteSpace(model.Password)) { var changePassRequest = new ChangePasswordRequest(model.Email, false, _customerSettings.DefaultPasswordFormat, model.Password); var changePassResult = await _customerRegistrationService.ChangePassword(changePassRequest); if (!changePassResult.Success) { foreach (var changePassError in changePassResult.Errors) { ErrorNotification(changePassError); } } } if (customer.IsAdmin() && !string.IsNullOrEmpty(model.VendorId)) { ErrorNotification(_localizationService.GetResource("Admin.Customers.Customers.AdminCouldNotbeVendor")); } if (newCustomerRoles.Any(x => x.SystemName == SystemCustomerRoleNames.Vendors) && string.IsNullOrEmpty(model.VendorId)) { ErrorNotification(_localizationService.GetResource("Admin.Customers.Customers.CannotBeInVendoRoleWithoutVendorAssociated")); } if (newCustomerRoles.Any(x => x.SystemName == SystemCustomerRoleNames.Staff) && string.IsNullOrEmpty(model.StaffStoreId)) { ErrorNotification(_localizationService.GetResource("Admin.Customers.Customers.CannotBeInStaffRoleWithoutStaffAssociated")); } if (customer.IsStaff() && customer.IsVendor()) { ErrorNotification(_localizationService.GetResource("Admin.Customers.Customers.VendorShouldNotbeStaff")); } SuccessNotification(_localizationService.GetResource("Admin.Customers.Customers.Added")); return(continueEditing ? RedirectToAction("Edit", new { id = customer.Id }) : RedirectToAction("List")); } //If we got this far, something failed, redisplay form await _customerViewModelService.PrepareCustomerModel(model, null, true); return(View(model)); }
/// <summary> /// Initiates the asynchronous execution of the ChangePassword operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ChangePassword operation on AmazonCognitoIdentityProviderClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndChangePassword /// operation.</returns> public IAsyncResult BeginChangePassword(ChangePasswordRequest request, AsyncCallback callback, object state) { var marshaller = new ChangePasswordRequestMarshaller(); var unmarshaller = ChangePasswordResponseUnmarshaller.Instance; return BeginInvoke<ChangePasswordRequest>(request, marshaller, unmarshaller, callback, state); }
/// <summary> /// Resets the password for a user. /// </summary> /// <param name="request"></param> public Response ResetPassword(ChangePasswordRequest request) { return(cruiseServer.ResetPassword(request)); }
public ChangePassordResponse ChangePassword(ChangePasswordRequest changePasswordRequest) { throw new NotImplementedException(); }
public ChangePasswordResponse ChangePassword(ChangePasswordRequest request) { var response = new ChangePasswordResponse(); try { if (WebSecurity.ChangePassword(request.UserName, request.OldPassword, request.NewPassword)) { response.Status = StatusCode.OK; } else { response.Status = StatusCode.Unauthorized; } } catch (Exception ex) { response.Status = StatusCode.InternalServerError; this.exceptionHandler.HandleException(ex); } return response; }
public async Task <ActionResult <SecurityResult> > ChangePassword([FromRoute] string userName, [FromBody] ChangePasswordRequest changePassword) { if (!IsUserEditable(userName)) { return(BadRequest(IdentityResult.Failed(new IdentityError { Description = "It is forbidden to edit this user." }).ToSecurityResult())); } var user = await _userManager.FindByNameAsync(userName); if (user == null) { return(BadRequest(IdentityResult.Failed(new IdentityError { Description = "User not found" }).ToSecurityResult())); } var result = await _signInManager.UserManager.ChangePasswordAsync(user, changePassword.OldPassword, changePassword.NewPassword); if (result.Succeeded && user.PasswordExpired) { user.PasswordExpired = false; await _userManager.UpdateAsync(user); } return(Ok(result.ToSecurityResult())); }
/// <summary> /// Changes the password for a specified user in a user pool. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ChangePassword service method.</param> /// /// <returns>The response from the ChangePassword service method, as returned by CognitoIdentityProvider.</returns> /// <exception cref="Amazon.CognitoIdentityProvider.Model.InternalErrorException"> /// This exception is thrown when Amazon Cognito encounters an internal error. /// </exception> /// <exception cref="Amazon.CognitoIdentityProvider.Model.InvalidParameterException"> /// This exception is thrown when the Amazon Cognito service encounters an invalid parameter. /// </exception> /// <exception cref="Amazon.CognitoIdentityProvider.Model.InvalidPasswordException"> /// This exception is thrown when the Amazon Cognito service encounters an invalid password. /// </exception> /// <exception cref="Amazon.CognitoIdentityProvider.Model.LimitExceededException"> /// This exception is thrown when a user exceeds the limit for a requested AWS resource. /// </exception> /// <exception cref="Amazon.CognitoIdentityProvider.Model.NotAuthorizedException"> /// This exception gets thrown when a user is not authorized. /// </exception> /// <exception cref="Amazon.CognitoIdentityProvider.Model.PasswordResetRequiredException"> /// This exception is thrown when a password reset is required. /// </exception> /// <exception cref="Amazon.CognitoIdentityProvider.Model.ResourceNotFoundException"> /// This exception is thrown when the Amazon Cognito service cannot find the requested /// resource. /// </exception> /// <exception cref="Amazon.CognitoIdentityProvider.Model.TooManyRequestsException"> /// This exception gets thrown when the user has made too many requests for a given operation. /// </exception> /// <exception cref="Amazon.CognitoIdentityProvider.Model.UserNotConfirmedException"> /// This exception is thrown when a user is not confirmed successfully. /// </exception> /// <exception cref="Amazon.CognitoIdentityProvider.Model.UserNotFoundException"> /// This exception is thrown when a user is not found. /// </exception> public ChangePasswordResponse ChangePassword(ChangePasswordRequest request) { var marshaller = new ChangePasswordRequestMarshaller(); var unmarshaller = ChangePasswordResponseUnmarshaller.Instance; return Invoke<ChangePasswordRequest,ChangePasswordResponse>(request, marshaller, unmarshaller); }
public Task <Response <UserModel> > ChangePassword(ChangePasswordRequest request, string aspNetUserId) { Response <UserModel> response = Response.ForError(""); return(Task.FromResult(response)); }
public ActionResult ChangePassword(ChangePasswordViewModel model) { if (this.ModelState.IsValid) { var request = new ChangePasswordRequest { UserName = "******", OldPassword = model.OldPassword, NewPassword = model.NewPassword }; var response = this.accountService.ChangePassword(request); if (response.Status == StatusCode.OK) { this.TempData["SuccessMessage"] = "You have successfully changed your password."; return this.RedirectToAction("Index"); } else { this.ViewBag.DisplaySummary = "yes"; this.ModelState.AddModelError(string.Empty, "Your old password has not been recognised. Please try again."); } } return this.View(); }
public async Task <ChangePasswordResponse> ChangePassword([FromBody] ChangePasswordRequest changePassword) { changePassword.ChangePassword.Token = HttpContext.Request.Headers["Authorization"].ToString().Replace("Bearer ", ""); return(await registerService.ChangePassword(changePassword)); }
public bool? ChangePassword(ChangePasswordRequest request, out int status, out string message) { status = 0; message = string.Empty; bool? response = null; try { IHttpOrderClient client = new HttpOrderClient(Publickey, true); var dic = new Dictionary<string, string>(); var url = GetUrl(BusinessObjectPublicUser.RequestFunction.ChangePassword); var result = client.Post(request, url, dic, Appid, Uid); if (result != null && result.ResponseData != null) { status = result.Status; message = result.Message; ResponseMessage = result.Message; Status = result.Status; return SerializerObject.ProtoBufDeserialize<bool>(result.ResponseData, client.Saltkey); } return null; } catch (Exception exception) { status = 0; message = "Lỗi từ user api"; ResponseMessage = SetResponseMessage(exception); return null; } }
public ChangePasswordResponse ChangePassword(ChangePasswordRequest request) { return(Execute <ChangePasswordRequest, ChangePasswordResponse>( request, response => _userFacade.ChangePassword(request.UserName, request.ActivationCode, request.Password))); }
public ChangePasswordViewModel Get(ChangePasswordRequest request) { return new ChangePasswordViewModel(); }
public async Task <ActionResult> ChangePassword(ChangePasswordRequest model) { var response = await _accountService.ChangePasswordAsync(model, _currentUser.UserId); return(Ok(response)); }
/// <summary> /// Changes the password of an account /// </summary> /// <param name="changePasswordRequest"></param> /// <param name="sessionToken"></param> /// <returns></returns> public async Task <AlpApiResponse> ChangePassword(ChangePasswordRequest changePasswordRequest, string sessionToken) { var response = new AlpApiResponse(); try { _logger.LogDebug(new { action = nameof(ChangePassword), sessionToken }.ToString()); if (string.IsNullOrEmpty(sessionToken)) { response.Success = false; response.Message = "Validásiós hiba a jelszóváltoztatás kérésben!"; return(response); } var session = _encryptionService.Decrypt <SessionTokenData>(sessionToken); if (session?.AccountId == null) { response.Success = false; response.Message = "Validásiós hiba a jelszóváltoztatás kérésben!"; return(response); } if (!changePasswordRequest.Validate()) { response.Success = false; response.Message = "Validációs hiba a jelszóváltoztatás kérésben!"; return(response); } var account = await _context.Account.FirstOrDefaultAsync(acc => acc.AccountId == session.AccountId); if (account == null) { response.Success = false; response.Message = "Nincs ilyen felhasználó az adatbázisban!"; return(response); } if (changePasswordRequest.OldPassword != account.Password) { response.Success = false; response.Message = "Hibás régi jelszó!"; return(response); } if (changePasswordRequest.OldPassword == changePasswordRequest.NewPassword) { response.Success = false; response.Message = "Az új jelszó nem egyezhet meg a régi jelszóval!"; return(response); } account.Password = changePasswordRequest.NewPassword; await _context.SaveChangesAsync(); } catch (Exception e) { _logger.LogError(new { exception = e, message = e.Message, innerException = e, innerExceptionMessage = e.InnerException?.Message }.ToString()); response.Message = e.Message; response.Success = false; } return(response); }
public virtual ActionResult Create(VendorModel model, bool continueEditing) { if (!_permissionService.Authorize(StandardPermissionProvider.ManageVendors)) { return(AccessDeniedView()); } if (ModelState.IsValid) { var cust1 = _customerService.GetCustomerByEmail(model.Email); if (cust1 != null) { ModelState.AddModelError("Email", "Email is already registered"); } var cust2 = _customerService.GetCustomerByUsername(model.AccountId); if (cust2 != null) { ModelState.AddModelError("AccountId", "Vendor account ID is already registered"); } if (!ModelState.IsValid) { return(View(model)); } var vendor = model.ToEntity(); _vendorService.InsertVendor(vendor); var customer = new Customer { CustomerGuid = Guid.NewGuid(), Email = model.Email, Username = model.AccountId, VendorId = vendor.Id, AdminComment = model.AdminComment, Active = model.Active, CreatedOnUtc = DateTime.UtcNow, LastActivityDateUtc = DateTime.UtcNow, RegisteredInStoreId = 0 }; _customerService.InsertCustomer(customer); var allCustomerRoles = _customerService.GetAllCustomerRoles(true); //customer roles foreach (var customerRole in allCustomerRoles) { //ensure that the current customer cannot add to "Administrators" system role if he's not an admin himself if (customerRole.SystemName == SystemCustomerRoleNames.Registered || customerRole.SystemName == SystemCustomerRoleNames.Vendors) { customer.CustomerRoles.Add(customerRole); } } //password if (!String.IsNullOrWhiteSpace(model.Password)) { var changePassRequest = new ChangePasswordRequest(model.Email, false, _customerSettings.DefaultPasswordFormat, model.Password); var changePassResult = _customerRegistrationService.ChangePassword(changePassRequest); if (!changePassResult.Success) { foreach (var changePassError in changePassResult.Errors) { ErrorNotification(changePassError); } } } if (string.IsNullOrWhiteSpace(model.Address.Address1)) { _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.StreetAddress, model.Address.Address1); } if (string.IsNullOrWhiteSpace(model.Address.Address2)) { _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.StreetAddress2, model.Address.Address2); } if (string.IsNullOrWhiteSpace(model.Address.ZipPostalCode)) { _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.ZipPostalCode, model.Address.ZipPostalCode); } if (string.IsNullOrWhiteSpace(model.Address.City)) { _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.City, model.Address.City); } if (model.Address.CountryId > 0) { _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.CountryId, model.Address.CountryId); } if (model.Address.StateProvinceId > 0) { _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.StateProvinceId, model.Address.StateProvinceId); } if (string.IsNullOrWhiteSpace(model.Address.PhoneNumber)) { _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.Phone, model.Address.PhoneNumber); } if (string.IsNullOrWhiteSpace(model.Address.FaxNumber)) { _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.Fax, model.Address.FaxNumber); } _customerService.UpdateCustomer(customer); //activity log _customerActivityService.InsertActivity("AddNewVendor", _localizationService.GetResource("ActivityLog.AddNewVendor"), vendor.Id); //search engine name model.SeName = vendor.ValidateSeName(model.SeName, vendor.Name, true); _urlRecordService.SaveSlug(vendor, model.SeName, 0); //address var address = model.Address.ToEntity(); address.CreatedOnUtc = DateTime.UtcNow; //some validation if (address.CountryId == 0) { address.CountryId = null; } if (address.StateProvinceId == 0) { address.StateProvinceId = null; } _addressService.InsertAddress(address); vendor.AddressId = address.Id; _vendorService.UpdateVendor(vendor); //locales UpdateLocales(vendor, model); //update picture seo file name UpdatePictureSeoNames(vendor); SuccessNotification(_localizationService.GetResource("Admin.Vendors.Added")); if (continueEditing) { //selected tab SaveSelectedTabName(); return(RedirectToAction("Edit", new { id = vendor.Id })); } return(RedirectToAction("List")); } //If we got this far, something failed, redisplay form PrepareVendorModel(model, null, true, true); return(View(model)); }
public UserEntity ChangePassword(ChangePasswordRequest request) { if (string.IsNullOrEmpty(request.oldPassword)) throw ModelException("oldPassword", AuthMessage.PasswordMustHaveAValue.NiceToString()); if (string.IsNullOrEmpty(request.newPassword)) throw ModelException("newPassword", AuthMessage.PasswordMustHaveAValue.NiceToString()); var user = UserEntity.Current; if (!user.PasswordHash.SequenceEqual(Security.EncodePassword(request.oldPassword))) throw ModelException("oldPassword", AuthMessage.InvalidPassword.NiceToString()); user.PasswordHash = Security.EncodePassword(request.newPassword); using (AuthLogic.Disable()) user.Execute(UserOperation.Save); return user; }
//Change Password public async Task<LoginUpdateInfo> GetChangePassword (ChangePasswordRequest password){ try{ return await service.ChangePassword(password, BearerToken); }catch(ApiException apie){ Insights.Report(apie, ReportSeverity.Error); throw; } }