public async Task <HttpResponseMessage> CreateGroup([FromBody] GroupDto group) { if (group == null) { throw new BadRequestException(ErrorMessages.GroupModelIsEmpty, ErrorCodes.BadRequest); } await _privilegesManager.Demand(Session.UserId, InstanceAdminPrivileges.ManageGroups); GroupValidator.ValidateModel(group, OperationMode.Create); int groupId = 0; Func <IDbTransaction, long, Task> action = async(transaction, transactionId) => { groupId = await _groupRepository.AddGroupAsync(group, transaction); var topRevisionId = await _itemInfoRepository.GetTopRevisionId(transaction); var groupIds = new[] { groupId }; var message = new UsersGroupsChangedMessage(new int[0], groupIds) { TransactionId = transactionId, RevisionId = topRevisionId, ChangeType = UsersGroupsChangedType.Create }; await _sendMessageExecutor.Execute(_applicationSettingsRepository, _serviceLogRepository, message, transaction); }; await RunInTransactionAsync(action); return(Request.CreateResponse(HttpStatusCode.Created, groupId)); }
public ICommandResult Handle(CreateGroupInput input) { var author = _userRepository.First(p => p.Username == input.Author); var group = new Group(input.Name, author, input.SocialMedia, input.Description); var validator = new GroupValidator().Validate(group); if (validator.IsValid) { _groupRepository.Create(group); } return(new CommandResult("Grupo criado com sucesso!", validator.Errors)); }
public bool ValidateInformation() { bool isValid = false; GroupValidator groupDataValidator = new GroupValidator(); ValidationResult dataValidationResult = groupDataValidator.Validate(Group); IList <ValidationFailure> validationFailures = dataValidationResult.Errors; UserFeedback userFeedback = new UserFeedback(FormGrid, validationFailures); userFeedback.ShowFeedback(); if (dataValidationResult.IsValid) { isValid = true; } return(isValid); }
public ICommandResult Handle(UpdateGroupInput input) { var group = _groupRepository.GetById(input.Id); group.Update(input.Name, input.Description); var validator = new GroupValidator().Validate(group); if (validator.IsValid) { _groupRepository.Update(group); } return(new CommandResult("Grupo atualizado com sucesso!", validator.Errors)); }
public void TestInitialize() { _groupValidator = new GroupValidator(); _group = new List <Group> { new Group { IdGroup = 1, Nrc = "12341", GroupStatus = GroupStatus.ACTIVE, Term = "FEBRERO-JUNIO 2021", StaffNumber = "65245" } }; _mockSetGroup = DbContextMock.GetQueryableMockDbSet(_group, g => g.IdGroup); _mockContext = DbContextMock.GetContext(_mockSetGroup); _unitOfWork = DbContextMock.GetUnitOfWork(_mockContext); }
public async Task <IHttpActionResult> UpdateGroup(int groupId, [FromBody] GroupDto group) { if (group == null) { throw new BadRequestException(ErrorMessages.GroupModelIsEmpty, ErrorCodes.BadRequest); } await _privilegesManager.Demand(Session.UserId, InstanceAdminPrivileges.ManageGroups); var existingGroup = await _groupRepository.GetGroupDetailsAsync(groupId); if (existingGroup == null || existingGroup.Id == 0) { throw new ResourceNotFoundException(ErrorMessages.GroupNotExist, ErrorCodes.ResourceNotFound); } GroupValidator.ValidateModel(group, OperationMode.Edit, existingGroup.ProjectId); Func <IDbTransaction, long, Task> action = async(transaction, transactionId) => { await _groupRepository.UpdateGroupAsync(groupId, group, transaction); var topRevisionId = await _itemInfoRepository.GetTopRevisionId(transaction); var groupIds = new[] { groupId }; var message = new UsersGroupsChangedMessage(new int[0], groupIds) { TransactionId = transactionId, RevisionId = topRevisionId, ChangeType = UsersGroupsChangedType.Update }; await _sendMessageExecutor.Execute(_applicationSettingsRepository, _serviceLogRepository, message, transaction); }; await RunInTransactionAsync(action); return(Ok()); }
public GroupsModule( GroupService groupService, GroupValidator validator, ILogger logger, IPropertySettings propertySettings = null) : base("/v1/groups", logger, validator, propertySettings) { _groupService = groupService; Post("/", async _ => await AddGroup(), null, "AddGroup"); Post("/UpdateGroups", async _ => await UpdateGroupList().ConfigureAwait(false), null, "UpdateGroups"); base.Get("/{groupName}", async p => await this.GetGroup(p).ConfigureAwait(false), null, "GetGroup"); base.Delete("/{groupName}", async p => await this.DeleteGroup(p).ConfigureAwait(false), null, "DeleteGroup"); // group->role mappings Get("/{groupName}/roles", async _ => await GetRolesFromGroup().ConfigureAwait(false), null, "GetRolesFromGroup"); Post("/{groupName}/roles", async _ => await AddRoleToGroup().ConfigureAwait(false), null, "AddRoleToGroup"); Delete("/{groupName}/roles", async _ => await DeleteRoleFromGroup().ConfigureAwait(false), null, "DeleteRoleFromGroup"); // (custom) group->user mappings Get("/{groupName}/users", async _ => await GetUsersFromGroup().ConfigureAwait(false), null, "GetUsersFromGroup"); Post("/{groupName}/users", async _ => await AddUserToGroup().ConfigureAwait(false), null, "AddUserToGroup"); Delete("/{groupName}/users", async _ => await DeleteUserFromGroup().ConfigureAwait(false), null, "DeleteUserFromGroup"); }
public GroupsModule( GroupService groupService, GroupValidator validator, ILogger logger, AccessService accessService, ClientService clientService, GrainService grainService, IdPSearchService idPSearchService, IAppConfiguration appConfiguration = null) : base("/v1/groups", logger, validator, accessService, appConfiguration) { _groupService = groupService; _clientService = clientService; _grainService = grainService; _idPSearchService = idPSearchService; Get("/", async _ => await GetGroups().ConfigureAwait(false), null, "GetGroups"); base.Get("/{groupName}", async _ => await GetGroup().ConfigureAwait(false), null, "GetGroup"); Post("/", async _ => await AddGroup().ConfigureAwait(false), null, "AddGroup"); Post("/UpdateGroups", async _ => await UpdateGroupList().ConfigureAwait(false), null, "UpdateGroups"); Patch("/{groupName}", async parameters => await this.UpdateGroup(parameters).ConfigureAwait(false), null, "UpdateGroup"); base.Delete("/{groupName}", async p => await this.DeleteGroup(p).ConfigureAwait(false), null, "DeleteGroup"); // group->role mappings Get("/{groupName}/roles", async _ => await GetRolesFromGroup().ConfigureAwait(false), null, "GetRolesFromGroup"); Get("/{groupName}/{grain}/{securableItem}/roles", async p => await GetRolesForGroup(p).ConfigureAwait(false), null, "GetRolesForGroup"); Post("/{groupName}/roles", async p => await AddRolesToGroup(p).ConfigureAwait(false), null, "AddRolesToGroup"); Delete("/{groupName}/roles", async p => await DeleteRolesFromGroup(p).ConfigureAwait(false), null, "DeleteRolesFromGroup"); // (custom) group->user mappings Get("/{groupName}/users", async _ => await GetUsersFromGroup().ConfigureAwait(false), null, "GetUsersFromGroup"); Post("/{groupName}/users", async p => await AddUsersToGroup(p).ConfigureAwait(false), null, "AddUserToGroup"); Delete("/{groupName}/users", async _ => await DeleteUserFromGroup().ConfigureAwait(false), null, "DeleteUserFromGroup"); // child groups Get("/{groupName}/groups", async p => await GetChildGroups(p).ConfigureAwait(false), null, "GetChildGroups"); Post("/{groupName}/groups", async p => await AddChildGroups(p).ConfigureAwait(false), null, "AddChildGroups"); Delete("/{groupName}/groups", async p => await RemoveChildGroups(p).ConfigureAwait(false), null, "RemoveChildGroups"); }
public void TestInitialize() { _groupValidator = new GroupValidator(); _practicioners = new List <Practicioner> { new Practicioner { Enrollment = "zS18012124", Term = "FEBRERO - JULIO 2021", Credits = 288, User = new User { IdUser = 1, Name = "Pedro", LastName = "Lopez", Gender = Gender.MALE, UserStatus = UserStatus.ACTIVE, Email = "*****@*****.**", AlternateEmail = "*****@*****.**", PhoneNumber = "2281456785", Account = new Account { Username = "******", Password = "******", FirstLogin = true } } }, new Practicioner { Enrollment = "zS18012125", Term = "FEBRERO - JULIO 2021", Credits = 288, User = new User { IdUser = 2, Name = "Priscila", LastName = "Luna", Gender = Gender.FEMALE, UserStatus = UserStatus.ACTIVE, Email = "*****@*****.**", AlternateEmail = "*****@*****.**", PhoneNumber = "2281456784", Account = new Account { Username = "******", Password = "******", FirstLogin = true } } }, new Practicioner { Enrollment = "zS18012126", Term = "FEBRERO - JULIO 2021", Credits = 288, User = new User { IdUser = 3, Name = "Pablo", LastName = "Lara", Gender = Gender.MALE, UserStatus = UserStatus.ACTIVE, Email = "*****@*****.**", AlternateEmail = "*****@*****.**", PhoneNumber = "2281456783", Account = new Account { Username = "******", Password = "******", FirstLogin = true } } }, new Practicioner { Enrollment = "zS18012127", Term = "FEBRERO - JULIO 2021", Credits = 288, User = new User { IdUser = 4, Name = "Patricio", LastName = "Lourdes", Gender = Gender.MALE, UserStatus = UserStatus.ACTIVE, Email = "*****@*****.**", AlternateEmail = "*****@*****.**", PhoneNumber = "2281456782", Account = new Account { Username = "******", Password = "******", FirstLogin = true } } }, new Practicioner { Enrollment = "zS18012128", Term = "FEBRERO - JULIO 2021", Credits = 288, User = new User { IdUser = 5, Name = "Patricia", LastName = "Lozcano", Gender = Gender.FEMALE, UserStatus = UserStatus.ACTIVE, Email = "*****@*****.**", AlternateEmail = "*****@*****.**", PhoneNumber = "2281456781", Account = new Account { Username = "******", Password = "******", FirstLogin = true } } } }; _teacher = new List <Teacher> { new Teacher { StaffNumber = "65245", RegistrationDate = DateTime.Now, DischargeDate = null, User = new User { IdUser = 6, Name = "Tamara", LastName = "Lopez", Gender = Gender.FEMALE, UserStatus = UserStatus.ACTIVE, Email = "*****@*****.**", AlternateEmail = "*****@*****.**", PhoneNumber = "2281456789", Account = new Account { Username = "******", Password = "******", FirstLogin = true } } } }; _group = new List <Group> { new Group { IdGroup = 1, Nrc = "12341", GroupStatus = GroupStatus.ACTIVE, Term = "FEBRERO-JUNIO 2021", StaffNumber = "65245" } }; _mockSetPracticioner = DbContextMock.GetQueryableMockDbSet(_practicioners, p => p.Enrollment); _mockContext = DbContextMock.GetContext(_mockSetPracticioner); _mockSetTeacher = DbContextMock.GetQueryableMockDbSet(_teacher, t => t.StaffNumber); _mockContext = DbContextMock.GetContext(_mockSetTeacher); _mockSetGroup = DbContextMock.GetQueryableMockDbSet(_group, g => g.IdGroup); _mockContext = DbContextMock.GetContext(_mockSetGroup); _unitOfWork = DbContextMock.GetUnitOfWork(_mockContext); }
public void TestInitialize() { var factory = AssemblyConfiguration.Kernel.Get <ValidatorFactory>(); _sut = factory.GetInstance <GroupValidator>(); }
// TODO Need to figure out how we rollback if cancellation is requested or prevent it? public async Task UpdateGroupMultipartDocument(Guid userId, string slug, byte[] rowVersion, Stream requestBody, string?contentType, CancellationToken cancellationToken) { var userCanPerformAction = await _permissionsService.UserCanPerformActionAsync(userId, slug, GroupEditRole, cancellationToken); if (userCanPerformAction is false) { _logger.LogError($"Error: CreateFileAsync - User:{0} does not have access to group:{1}", userId, slug); throw new SecurityException($"Error: User does not have access"); } var groupDto = await _groupCommand.GetGroupAsync(slug, cancellationToken); if (!groupDto.RowVersion.SequenceEqual(rowVersion)) { _logger.LogError($"Precondition Failed: UpdateGroupAsync - Group:{0} has changed prior to submission ", slug); throw new PreconditionFailedExeption("Precondition Failed: Group has changed prior to submission"); } var(group, image) = await UploadGroupImageMultipartContent(groupDto, userId, slug, requestBody, rowVersion, contentType, cancellationToken); var groupValidator = new GroupValidator(); var groupValidationResult = await groupValidator.ValidateAsync(group, cancellationToken); if (groupValidationResult.Errors.Count > 0) { throw new ValidationException(groupValidationResult); } try { if (image is not null) { var imageId = await _imageService.CreateImageAsync(image); group = group with { ImageId = imageId }; } } catch (DBConcurrencyException ex) { _logger.LogError(ex, $"Error: CreateImageAsync - Error adding image to group {0}", slug); if (image is not null) { await _blobStorageProvider.DeleteFileAsync(image.FileName); await _imageService.DeleteImageAsync(image.Id); } } try { await UpdateGroupAsync(userId, slug, group, cancellationToken); } catch (DBConcurrencyException ex) { _logger.LogError(ex, $"Error: UpdateGroupAsync - Error updating group {0}", slug); if (image is not null) { await _blobStorageProvider.DeleteFileAsync(image.FileName); await _imageService.DeleteImageAsync(image.Id); } } //TODO - Delete old image of everything succeeds and the image has been removed or replaced }
public async Task CreateGroupAsync(Guid userId, Stream requestBody, string?contentType, CancellationToken cancellationToken) { var now = _systemClock.UtcNow.UtcDateTime; var userCanPerformAction = await _permissionsService.UserCanPerformActionAsync(userId, AddGroupRole, cancellationToken); if (userCanPerformAction is not true) { _logger.LogError($"Error: CreateGroupAsync - User:{0} does not have access to add group:{1}", userId); throw new SecurityException($"Error: User does not have access"); } var(group, image) = await AdminUploadGroupImageMultipartContent(userId, requestBody, contentType, cancellationToken); if (image is not null) { try { var imageId = await _imageService.CreateImageAsync(image); group = group with { ImageId = imageId }; } catch (DBConcurrencyException ex) { _logger.LogError(ex, $"Error: CreateImageAsync - Error creating image {0}", null); if (image is not null) { await _blobStorageProvider.DeleteFileAsync(image.FileName); await _imageService.DeleteImageAsync(image.Id); } throw new DBConcurrencyException("Error: User request to create an image was not successful"); } } var groupValidator = new GroupValidator(); var groupValidationResult = await groupValidator.ValidateAsync(group, cancellationToken); if (groupValidationResult.Errors.Count > 0) { throw new ValidationException(groupValidationResult); } var groupSiteDto = new GroupSiteDto() { CreatedAtUTC = now, CreatedBy = userId, }; try { groupSiteDto.GroupId = await _groupCommand.CreateGroupAsync(userId, group, cancellationToken); } catch (DBConcurrencyException ex) { if (image is not null) { await _blobStorageProvider.DeleteFileAsync(image.FileName); await _imageService.DeleteImageAsync(image.Id); } _logger.LogError(ex, $"Error: CreateGroupAsync - Error creating group {0}", null); throw new DBConcurrencyException("Error: User request to create a group was not successful"); } // Create the group homepage content in Umbraco var createContentResponse = await _contentService.CreatePageAsync(userId, groupSiteDto.GroupId, null, cancellationToken); // If the create content request fails, delete the associated group if (createContentResponse is null || !createContentResponse.Succeeded) { //TODO: rollback/delete group (feature: 75323) _logger.LogError($"Error: CreatePageAsync - Error creating group homepage content {groupSiteDto.GroupId}"); throw new HttpRequestException($"Error: CreatePageAsync - Error creating group homepage content {groupSiteDto.GroupId}"); } try { groupSiteDto.ContentRootId = Guid.Parse(createContentResponse.Data); await _groupCommand.CreateGroupSiteAsync(groupSiteDto, cancellationToken); } catch (DBConcurrencyException ex) { _logger.LogError(ex, $"Error: CreateGroupSiteAsync - Error creating group site {0}"); throw new DBConcurrencyException("Error: User request to create a group site was not successful"); } }