public DeleteUserResponse Delete(DeleteUserRequest request) { DeleteUserResponse response = new DeleteUserResponse(); User user = _userRepository.Get(request.Id); if (user == null) { response.HasError = true; response.Message = "User not found"; return(response); } if (user.Id == request.CurrentUserID) { throw new InvalidOperationException("You cannot delete yourself!"); } // must remove all role memberships before deleting user.RemoveFromAllRoles(); _userRepository.Delete(user); _unitOfWork.Commit(); return(response); }
internal virtual DeleteUserResponse DeleteUser(DeleteUserRequest request) { var marshaller = DeleteUserRequestMarshaller.Instance; var unmarshaller = DeleteUserResponseUnmarshaller.Instance; return(Invoke <DeleteUserRequest, DeleteUserResponse>(request, marshaller, unmarshaller)); }
public void DeleteUserTest() { var testGuid = Guid.NewGuid(); var usersRequest = new DeleteUserRequest(testGuid); var expectedUser = new Domain.User.User { Id = Guid.NewGuid(), FirstName = "test", LastName = "test", Address = new Address { Country = "UK" } }; var mockUow = new Mock <IUnitOfWork>(); var mockRepo = new Mock <IUserRepository>(); mockRepo.Setup(x => x.Delete(expectedUser)); mockRepo.Setup(x => x.FindBy(usersRequest.Id)).Returns(expectedUser); var mockMapper = new Mock <IUserDtoMapper>(); var mockValidator = new Mock <IValidator <Domain.User.User> >(); var service = new UserService(mockUow.Object, mockRepo.Object, mockMapper.Object, mockValidator.Object); var response = service.DeleteUser(usersRequest); Assert.IsTrue(response.Result); Assert.IsNull(response.Exception); mockRepo.Verify(x => x.Delete(expectedUser), Times.Once); mockUow.Verify(x => x.Commit(), Times.Once); }
public async Task DeleteUserAsyncTest() { // Create new user var newUser = await UserHelper.CreateNewUserAsync(); // Authenticate the user var token = await UserHelper.AuthenticateAsync(newUser.Username, newUser.Password); App.UserToken = token; // Delete the user var request = new DeleteUserRequest() { UserId = newUser.Id }; var response = await request.ExecuteAsync(); ApiHelper.EnsureValidResponse(response); // Try to get the user var getResponse = await(new GetUserRequest() { UserId = newUser.Id }).ExecuteAsync(); ApiHelper.EnsureValidResponse(getResponse, false); Assert.IsFalse(getResponse.Status.IsSuccessful, "Get for an non-existant user did not fail."); Console.WriteLine("Get user error message: {0}", getResponse.Status.Message); }
public ActionResult <DeleteUserResponse> Delete([FromBody] DeleteUserRequest request) { request.CommanderID = User.GetUserId(); var result = _userService.Delete(request); return(result); }
public void DeletaUsuarioIdQueNaoExiste() { #region Parameters int userId = 00; //Resultado Esperado string statusCodeExpected = "BadRequest"; #endregion DeleteUserRequest deleteUserRequest = new DeleteUserRequest(userId); IRestResponse <dynamic> response = deleteUserRequest.ExecuteRequest(); Assert.AreEqual(statusCodeExpected, response.StatusCode.ToString(), "O StatusCode retornado não é o esperado."); string[] arrayRegex = new string[] { "\"message\":\"Invalid user id\"", "\"localized\":\"Invalid value for 'id'\"", }; MatchCollection matches; foreach (string regex in arrayRegex) { matches = new Regex(regex).Matches(response.Content); Assert.That(matches.Count > 0, "Esperado: " + regex + " Encontrado:" + response.Content); } }
public async Task <IActionResult> DeleteUserConfirmedByToken(DeleteUserRequest request) { var accessToken = HttpContext.Request.Headers["Authorization"].ToString(); if (accessToken == null) { return(NotFound("Something is wrong with your authorization token")); } if (request == null) { return(BadRequest("You must fill in all the fields")); } DeleteUserResponse deletionResult = await _identityService.DeleteUserByIdIfTokenHasSameAspNetUserId(request.aspUserId, accessToken); if (deletionResult.Success) { _logger.LogInfo($"Delete user with {request.aspUserId} succeded"); return(Ok(new SimpleSuccessResponse { Success = true, Message = "Confirm, user deleted" })); } else { _logger.LogError("Delete user error occured : " + deletionResult.Errors); return(BadRequest($"User deletion failed.{deletionResult.Message}")); } }
internal bool DeleteUser(DeleteUserRequest request) { var conn = GetConnection(ConnectionNames.CSPSqlDatabase); var commandWrapper = GetStoredProcCommand("dbo.Delete_User_Data", conn); AddInParameter(commandWrapper, "@UserId", DbType.Int16, request.UserId); AddInParameter(commandWrapper, "@ERROR", DbType.String, 1000); AddInParameter(commandWrapper, "@ERROR_CODE", DbType.String, 4); try { conn.Open(); int results = commandWrapper.ExecuteNonQuery(); var isProcedureSucced = Convert.ToBoolean(results); MakeDboLog(request.ToString(), isProcedureSucced.ToString(), "dbo.Delete_User_Data"); var errorObject = GetParameterValue(commandWrapper, "@ERROR"); var errorCodeObject = GetParameterValue(commandWrapper, "@ERROR_CODE"); return Convert.ToBoolean(results); } finally { commandWrapper.Dispose(); conn.Close(); } }
/// <summary> /// Deletes the user. /// </summary> /// <param name="storefront">The storefront.</param> /// <param name="visitorContext">The visitor context.</param> /// <returns> /// The manager response where the success flag is returned in the result. /// </returns> public virtual ManagerResponse <DeleteUserResult, bool> DeleteUser([NotNull] CommerceStorefront storefront, [NotNull] VisitorContext visitorContext) { Assert.ArgumentNotNull(storefront, "storefront"); Assert.ArgumentNotNull(visitorContext, "visitorContext"); var userName = visitorContext.UserName; var commerceUser = this.GetUser(userName).Result; if (commerceUser != null) { // NOTE: we do not need to call DeleteCustomer because this will delete the commerce server user under the covers var request = new DeleteUserRequest(new CommerceUser { UserName = userName }); var result = this.CustomerServiceProvider.DeleteUser(request); if (!result.Success) { Helpers.LogSystemMessages(result.SystemMessages, result); } return(new ManagerResponse <DeleteUserResult, bool>(result, result.Success)); } return(new ManagerResponse <DeleteUserResult, bool>(new DeleteUserResult { Success = false }, false)); }
public async Task <IActionResult> DeleteUser([FromRoute] int id) { if (!ModelState.IsValid) { return(BadRequest()); } // We check if the user exists. ExistsUserRequest existsRequest = new ExistsUserRequest() { Id = id }; var exists = await _mediator.Send(existsRequest); if (!exists) { return(StatusCode(StatusCodes.Status404NotFound, "The user was not found.")); } DeleteUserRequest request = new DeleteUserRequest() { Id = id }; // Removing the user, this is a hard remove, we could create // a soft if we can create a UNDO method. var deletedId = await _mediator.Send(request); return(Ok(deletedId)); }
public async Task <HandlerResponse <bool> > Handle(DeleteUserRequest request, CancellationToken cancellationToken) { HandlerResponse <bool> response; var user = await _dataContext.Users.SingleOrDefaultAsync(u => u.Id == request.Id, cancellationToken); if (user is null) { response = new HandlerResponse <bool>(true, "User was not present"); } else { try { _dataContext.Users.Remove(user); await _dataContext.SaveChangesAsync(cancellationToken); response = new HandlerResponse <bool>(true); } catch (DbException) { response = new HandlerResponse <bool>($"Unable to delete User"); } } return(response); }
public async Task <bool> Handle(DeleteUserRequest message, IOutputPort <DeleteUserResponse> outputPort) { var response = await _userRepository.Delete(new DomainEntities.User(message.FirstName, message.LastName, message.Email, message.RoleId)); outputPort.Handle(response.Success ? new DeleteUserResponse(response.Id, true) : new DeleteUserResponse(response.Errors.Select(e => e.Description))); return(response.Success); }
public DeleteUserResponse DeleteUser(DeleteUserRequest request) { bool deleted = false; if (request == null) { return(new DeleteUserResponse { Success = false, Message = "Error, request is null" }); } deleted = _service.Delete(request.UserId); if (!deleted) { return(new DeleteUserResponse { Success = false, Message = "Error, unable to delete" }); } return(new DeleteUserResponse { Success = true, Message = "The user has been deleted successfully" }); }
public void Delete(DeleteUserRequest request) { IDocumentStore store = DocumentStoreHolder.Store; using (var storeSession = store.OpenSession()) { var session = this.GetSession(); storeSession.Delete(request.UserId); var parentUser = storeSession.Load <User>(session.UserAuthId); if (parentUser.UserIds != null) { parentUser.UserIds.Remove(request.UserId); } var logItem = new LogItem { User = parentUser, OldValue = request.ToJson(), TimeStamp = DateTime.UtcNow, Url = base.Request.AbsoluteUri, IpAddress = base.Request.RemoteIp, Action = "Delete User" }; storeSession.Store(logItem); storeSession.SaveChanges(); } }
public async Task DeleteUser() { if (userId == -1) { return; } var deleteUserRequest = new DeleteUserRequest() { IdToDelete = userId, AccessToken = token }; using var client = GetHttpClient(); var requestContent = GetHttpContent(JsonSerializer.Serialize <DeleteUserRequest>(deleteUserRequest, jsonSerializerOptions)); var request = new HttpRequestMessage(HttpMethod.Delete, $"{baseUrl}/api/user") { Content = requestContent }; var response = await client.SendAsync(request); if (response.StatusCode != HttpStatusCode.OK) { var responseContent = await response.Content.ReadAsStringAsync(); DispatchEvent(OnError, new UserClientErrorEventArgs($"Error deleting user: {response.StatusCode} : {responseContent}")); } userId = -1; token = string.Empty; tokenExpires = DateTime.MinValue; }
public void DeleteUser(DeleteUserRequest request) { 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.Username, "Username"); Common.Helpers.ValidationHelper.ValidateStringLength(request.Username, "Username", Constants.MaxUsernameLength); if (!UserController.ValidateSession(request.AuthToken, out authToken)) { throw new AuthenticationException("Authentication failed."); } UserController.ValidateAntiForgeryToken(request.AntiForgeryToken, authToken); UserController.DeleteUser(request.Username, authToken); } catch (AuthenticationException ex) { throw new WebFaultException <string>(ex.Message, System.Net.HttpStatusCode.BadRequest); } catch (Common.Exceptions.ValidationException ex) { throw new WebFaultException <string>(ex.Message, System.Net.HttpStatusCode.BadRequest); } catch (Exception ex) { ExceptionHelper.Log(ex, authToken == null ? null : authToken.Username); throw new WebFaultException <string>("An unknown error has occurred.", System.Net.HttpStatusCode.InternalServerError); } }
/// <inheritdoc /> public async Task <ResultMessage> DeleteUserAsync(DeleteUserRequest request) { if (request == null) { throw new ArgumentNullException(nameof(request)); } User identityUser = await _userManager.FindByNameAsync(request.Login).ConfigureAwait(false); IList <string> identityUserRoles = await _userManager.GetRolesAsync(identityUser).ConfigureAwait(false); if (identityUserRoles.Contains("ADMINISTRATOR")) { return(new ResultMessage { OperationStatus = false, ErrorMessages = new List <string> { MessageResources.DeleteAdministrator } }); } IdentityResult result = await _userManager.DeleteAsync(identityUser).ConfigureAwait(false); return(new ResultMessage { OperationStatus = result.Succeeded, ErrorMessages = result.Errors?.Select(err => err.Description) }); }
public async Task DeleteUserAsync_NotNullRequest_UserNotAdmin_OkDeletion_ReturnSuccessMessage() { // Arrange DeleteUserRequest request = new DeleteUserRequest { Login = "******" }; User identityUser = new User { UserName = request.Login }; _userManagerMock.Setup(mock => mock.FindByNameAsync(request.Login)).ReturnsAsync(identityUser); _userManagerMock.Setup(mock => mock.GetRolesAsync(identityUser)).ReturnsAsync( new List <string> { "hawRole" }); _userManagerMock.Setup(mock => mock.DeleteAsync(identityUser)).ReturnsAsync(IdentityResult.Success); // Act ResultMessage resultMessage = await _identityService.DeleteUserAsync(request).ConfigureAwait(false); // Assert Assert.NotNull(resultMessage); Assert.True(resultMessage.OperationStatus); }
public DeleteUserResponse DeleteUser(DeleteUserRequest request) { var response = new DeleteUserResponse(); try { var task = _userRepository.FindBy(request.Id); if (task != null) { _userRepository.Delete(task); _uow.Commit(); response.Result = true; return(response); } response.Exception = GetStandardUserNotFoundException(); return(response); } catch (Exception ex) { response.Exception = ex; return(response); } }
public async Task DeleteUserAsync_NotNullRequest_UserAdmin_ReturnFailingMessage() { // Arrange DeleteUserRequest request = new DeleteUserRequest { Login = "******" }; User identityUser = new User { UserName = request.Login }; _userManagerMock.Setup(mock => mock.FindByNameAsync(request.Login)).ReturnsAsync(identityUser); _userManagerMock.Setup(mock => mock.GetRolesAsync(identityUser)).ReturnsAsync( new List <string> { "ADMINISTRATOR" }); // Act ResultMessage resultMessage = await _identityService.DeleteUserAsync(request).ConfigureAwait(false); // Assert Assert.NotNull(resultMessage); Assert.False(resultMessage.OperationStatus); Assert.Equal(MessageResources.DeleteAdministrator, resultMessage.ErrorMessages.First()); }
public async Task DeleteUserByIdAsync(DeleteUserRequest request) { var user = await this.database.Users.SingleAsync(x => x.Id == request.UserId); this.database.Users.Remove(user); await this.database.SaveChangesAsync(); }
public async Task DeleteUserAsync_NotNullRequest_UserNotAdmin_FailedDeletion_ReturnFailingMessage() { // Arrange DeleteUserRequest request = new DeleteUserRequest { Login = "******" }; User identityUser = new User { UserName = request.Login }; string errorMessage = "nelson: haw haw"; _userManagerMock.Setup(mock => mock.FindByNameAsync(request.Login)).ReturnsAsync(identityUser); _userManagerMock.Setup(mock => mock.GetRolesAsync(identityUser)).ReturnsAsync( new List <string> { "hawRole" }); _userManagerMock.Setup(mock => mock.DeleteAsync(identityUser)).ReturnsAsync(IdentityResult.Failed( new IdentityError { Description = errorMessage })); // Act ResultMessage resultMessage = await _identityService.DeleteUserAsync(request).ConfigureAwait(false); // Assert Assert.NotNull(resultMessage); Assert.False(resultMessage.OperationStatus); Assert.Equal(errorMessage, resultMessage.ErrorMessages.First()); }
public void DeletaUsuarioComSucesso() { #region Inserindo um novo usuário string username = "******"; usersDBSteps.InseriUsuarioDB(username); var consultaUsuarioDB = usersDBSteps.ConsultaUsuarioDB(username); #endregion #region Parameters int userId = int.Parse(consultaUsuarioDB.UserId); //Resultado Esperado string statusCodeExpected = "NoContent"; #endregion DeleteUserRequest deleteUserRequest = new DeleteUserRequest(userId); IRestResponse <dynamic> response = deleteUserRequest.ExecuteRequest(); consultaUsuarioDB = usersDBSteps.ConsultaUsuarioDB(username); Assert.Multiple(() => { Assert.AreEqual(statusCodeExpected, response.StatusCode.ToString(), "O StatusCode retornado não é o esperado."); Assert.IsNull(consultaUsuarioDB, "O usuário não foi excluído."); }); }
public async Task <IActionResult> Delete(Guid id) { var deleteUserRequest = new DeleteUserRequest(id); await _deleteUserUseCase.Handle(deleteUserRequest, _deleteUserPresenter); return(_deleteUserPresenter.ActionResult); }
/// <summary> /// 删除用户 /// </summary> /// <param name="request"></param> /// <returns></returns> public bool DeleteUser(DeleteUserRequest request) { //删除用户表数据 //解除用户-机构的关系 //解除用户-角色的关系 //需要使用事务 var result = false; List <int> ids = request.Ids.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).Select(p => p.ToInt()).ToList(); using (var conn = DapperHelper.CreateConnection()) { var trans = conn.BeginTransaction(); try { //删除用户数据 conn.Execute(@"DELETE FROM dbo.t_rights_user WHERE id IN @Ids;", new { @Ids = ids }, trans); //删除用户-机构数据 conn.Execute(@"DELETE FROM dbo.t_rights_user_organization WHERE user_id IN @Ids;", new { @Ids = ids }, trans); //删除用户-角色数据 conn.Execute(@"DELETE FROM dbo.t_rights_user_role WHERE user_id IN @Ids;", new { @Ids = ids }, trans); trans.Commit(); result = true; } catch (Exception ex) { trans.Rollback(); } } return(result); }
public async Task <IActionResult> DeleteUserAsync(DeleteUserRequest request) { if (request == null) { return(BadRequest(new ResultMessage { OperationStatus = false, ErrorMessages = new List <string> { MessageResources.UserDeletionRequestEmpty } })); } try { ResultMessage result = await _identityService.DeleteUserAsync(request).ConfigureAwait(false); return(Ok(result)); } catch (Exception) { return(StatusCode(500, new ResultMessage { OperationStatus = false, ErrorMessages = new List <string> { MessageResources.UserDeletionFailed } })); } }
protected override void ProcessRecord() { base.ProcessRecord(); if (!ConfirmDelete("OCIIdentityUser", "Remove")) { return; } DeleteUserRequest request; try { request = new DeleteUserRequest { UserId = UserId, IfMatch = IfMatch }; response = client.DeleteUser(request).GetAwaiter().GetResult(); WriteOutput(response); FinishProcessing(response); } catch (Exception ex) { TerminatingErrorDuringExecution(ex); } }
public DeleteUserResponse DeleteUser(DeleteUserRequest request) { var response = new DeleteUserResponse { ResponseStatus = ResponseStatus.Success }; var usersProvider = new UsersProvider(); try { if (request.ActionType == ActionType.Delete) { response.isSuccessful = usersProvider.DeleteUser(request); } else { response.ResponseStatus = ResponseStatus.Failure; response.ResponseDescription = "Not update action"; } } catch (Exception ex) { response.ResponseStatus = ResponseStatus.Failure; response.ResponseDescription = ex.Message; } return(response); }
public void DeleteUserTest() { var testGuid = Guid.NewGuid(); var request = new DeleteUserRequest(testGuid); var expectedResonse = new DeleteUserResponse { Exception = null }; var mockService = new Mock <IUserService>(); mockService.Setup(x => x.DeleteUser(request)).Returns(expectedResonse); var mockLogger = new Mock <ILoggingService>(); var mockEmail = new Mock <IEmailService>(); var mockConfig = new Mock <IAppConfig <IServiceConfigOptions> >(); var service = new EnrichedUserService(mockService.Object, mockLogger.Object, mockEmail.Object, mockConfig.Object); var response = service.DeleteUser(request); Assert.IsNull(response.Exception); Assert.AreEqual(expectedResonse.Exception, response.Exception); mockService.Verify(x => x.DeleteUser(request), Times.Once); }
public async Task <RequestResult> DeleteUser() { RequestResult result = new RequestResult(); try { if (cognitoUserSession != null && cognitoUserSession.IsValid()) { DeleteUserRequest dr = new DeleteUserRequest() { AccessToken = cognitoUserSession.AccessToken }; await provider.DeleteUserAsync(dr); result.Status = true; result.Message = "Deleted Successfully"; } else { //this.RefreshToken(username); result.Status = false; result.Message = "Not valid session"; } } catch (Exception ex) { result.Status = false; result.Message = ex.Message; } return(result); }
private void btnDelete_Click(object sender, EventArgs e) { if (dgvUsers.CurrentRow == null) SOAFramework.Client.Controls.MessageBox.Show(this, "请选择一条数据"); else if (SOAFramework.Client.Controls.MessageBox.Show(this, "是否删除选中数据?", "警告", MessageBoxButtons.YesNo) == DialogResult.Yes) { List<string> list = new List<string>(); var user = dgvUsers.CurrentRow.DataBoundItem as FullUser; list.Add(user.ID); DeleteUserRequest request = new DeleteUserRequest(); request.token = AppData.token; request.IDs = list; SDKSync<CommonResponse>.CreateInstance(this).Execute(request, btnDelete_ClickCallback); } }
private void button8_Click(object sender, EventArgs e) { DeleteUserRequest request = new DeleteUserRequest(); request.token = token; request.userid = user.ID; var response = SDKFactory.Client.Execute(request); MessageBox.Show(response.ResponseBody); }
public DeleteUserResponse Delete(DeleteUserRequest request) { throw new CmsException(UsersApiConstants.UsersApiHasNoImplementationMessage); }
public DeleteUserResponse Delete(DeleteUserRequest request) { userService.DeleteUser(request.Id, request.Data.Version); return new DeleteUserResponse { Data = true }; }
/// <summary> /// Deletes the user. /// </summary> /// <param name="storefront">The storefront.</param> /// <param name="visitorContext">The visitor context.</param> /// <returns> /// The manager response where the success flag is returned in the result. /// </returns> public virtual ManagerResponse<DeleteUserResult, bool> DeleteUser([NotNull] CommerceStorefront storefront, [NotNull] VisitorContext visitorContext) { Assert.ArgumentNotNull(storefront, "storefront"); Assert.ArgumentNotNull(visitorContext, "visitorContext"); var userName = visitorContext.UserName; var commerceUser = this.GetUser(userName).Result; if (commerceUser != null) { // NOTE: we do not need to call DeleteCustomer because this will delete the commerce server user under the covers var request = new DeleteUserRequest(new CommerceUser { UserName = userName }); var result = this.CustomerServiceProvider.DeleteUser(request); Helpers.LogSystemMessages(result.SystemMessages, result); return new ManagerResponse<DeleteUserResult, bool>(result, result.Success); } return new ManagerResponse<DeleteUserResult, bool>(new DeleteUserResult() { Success = false }, false); }