示例#1
0
        public async Task <Role> CreateAsync(RoleSubmit roleSubmit, Guid createdById)
        {
            // Start transactions to allow complete rollback in case of an error
            InitSharedTransaction();

            try
            {
                RoleModel existingRole = await roleRepository.GetByNameAsync(roleSubmit.Name);

                if (existingRole != null)
                {
                    throw new ItemNotProcessableException($"Role with Name '{roleSubmit.Name}' already exist.");
                }

                // Note: The mapper will only map the basic first level members of the RoleSubmit to the Role.
                // The RoleSubmit contains a list of User UUIDs that will need to be found and converted into actual user representations.
                RoleModel newRole = mapper.Map <RoleModel>(roleSubmit);
                newRole.ChangedBy = createdById;

                // The potentially assigned sub-realm is used within the 'AssignFunctionsToRoleFromFunctionIdList' function, so perform sub-realm assignmentd first.
                await CheckForSubRealmAndAssignToRoleIfExists(newRole, roleSubmit);
                await AssignFunctionsToRoleFromFunctionIdList(newRole, roleSubmit.FunctionIds);
                await AssignRolesToRoleFromRolesIdList(newRole, roleSubmit.RoleIds);

                // All successful
                CommitTransaction();

                return(mapper.Map <Role>(await roleRepository.CreateAsync(newRole)));
            }
            catch
            {
                RollbackTransaction();
                throw;
            }
        }
示例#2
0
        public async Task <Role> CreateAsync(RoleSubmit roleSubmit, Guid createdById)
        {
            // Start transactions to allow complete rollback in case of an error
            BeginAllTransactions();

            try
            {
                // Note: The mapper will only map the basic first level members of the RoleSubmit to the Role.
                // The RoleSubmit contains a list of User UUIDs that will need to be found and converted into actual user representations.
                RoleModel newRole = mapper.Map <RoleModel>(roleSubmit);
                newRole.ChangedBy = createdById;

                await AssignUsersToRoleFromUserIdList(newRole, roleSubmit.UserIds);
                await AssignFunctionsToRoleFromFunctionIdList(newRole, roleSubmit.FunctionIds);
                await AssignRolesToRoleFromRolesIdList(newRole, roleSubmit.RoleIds);

                // All successful
                CommitAllTransactions();

                return(mapper.Map <Role>(await roleRepository.CreateAsync(newRole)));
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                RollbackAllTransactions();
                throw;
            }
        }
示例#3
0
        public async Task <Role> UpdateAsync(RoleSubmit roleSubmit, Guid updatedById)
        {
            // Start transactions to allow complete rollback in case of an error
            InitSharedTransaction();

            try
            {
                // Note: The mapper will only map the basic first level members of the RoleSubmit to the Role.
                // The RoleSubmit contains a list of User UUIDs that will need to be found and converted into actual user representations.
                RoleModel role = await roleRepository.GetByIdAsync(roleSubmit.Uuid);

                if (role == null)
                {
                    throw new ItemNotFoundException($"Role with ID '{roleSubmit.Uuid}' not found when attempting to update a role using this ID!");
                }

                if (role.Name != roleSubmit.Name)
                {
                    // Confirm the new name is available
                    var checkExistingNameModel = await roleRepository.GetByNameAsync(roleSubmit.Name);

                    if (checkExistingNameModel != null)
                    {
                        throw new ItemNotProcessableException($"Role with name '{roleSubmit.Name}' already exists.");
                    }
                }

                // Confirm this role isn't becoming a compound role while already part of a compound role
                if (roleSubmit.RoleIds.Any() && role.ParentRoles != null && role.ParentRoles.Any())
                {
                    throw new ItemNotProcessableException($"This role is already part of a compound role, and as such, cannot become a compound role itself.");
                }

                role.Name        = roleSubmit.Name;
                role.Description = roleSubmit.Description;
                role.ChangedBy   = updatedById;

                await AssignFunctionsToRoleFromFunctionIdList(role, roleSubmit.FunctionIds);

                // Note: Sub-realm of a role cannot be changed once created. Hence the absence of a call to 'CheckForSubRealmAndAssignToRoleIfExists'.
                await AssignRolesToRoleFromRolesIdList(role, roleSubmit.RoleIds);

                // All successful
                CommitTransaction();

                return(mapper.Map <Role>(await roleRepository.UpdateAsync(role)));
            }
            catch
            {
                RollbackTransaction();
                throw;
            }
        }
示例#4
0
        private async Task CheckForSubRealmAndAssignToRoleIfExists(RoleModel role, RoleSubmit roleSubmit)
        {
            // Recall that submit models with empty GUIDs will not be null but rather Guid.Empty.
            if (roleSubmit.SubRealmId == null || roleSubmit.SubRealmId == Guid.Empty)
            {
                return;
            }

            var existingSubRealm = await subRealmRepository.GetByIdAsync(roleSubmit.SubRealmId, false);

            role.SubRealm = existingSubRealm ?? throw new ItemNotFoundException($"Sub-realm with ID '{roleSubmit.SubRealmId}' does not exist.");
        }
示例#5
0
        public async Task UpdateRoleAsync_WithTestRole_ReturnsUpdatedRole()
        {
            // Arrange
            var roleService = Substitute.For <IRoleService>();
            var inputModel  = new RoleSubmit()
            {
                Uuid    = Guid.NewGuid(),
                Name    = "Test Role Name",
                UserIds = new List <Guid>()
                {
                    new Guid(),
                    new Guid()
                },
                FunctionIds = new List <Guid>()
                {
                    new Guid(),
                    new Guid(),
                }
            };

            roleService.UpdateAsync(inputModel, Arg.Any <Guid>())
            .Returns(new Role()
            {
                Uuid        = inputModel.Uuid,
                Name        = inputModel.Name,
                UserIds     = inputModel.UserIds,
                FunctionIds = inputModel.FunctionIds
            }
                     );

            var controller = new RoleController(roleService);

            // Act
            IActionResult actionResult = await controller.UpdateRoleAsync(inputModel.Uuid, inputModel);

            // Assert
            var okResult = actionResult as OkObjectResult;

            Assert.NotNull(okResult);

            var role = okResult.Value as Role;

            Assert.NotNull(role);
            Assert.True(role.Uuid == inputModel.Uuid, $"Retrieved Id {role.Uuid} not the same as sample id {inputModel.Uuid}.");
            Assert.True(role.Name == inputModel.Name, $"Retrieved Name {role.Name} not the same as sample Name {inputModel.Name}.");
            Assert.True(role.UserIds.Count == 2, $"Retrieved UserIds count {role.UserIds.Count} not the same as sample UserIds count {inputModel.UserIds.Count}.");
            Assert.True(role.UserIds[0] == inputModel.UserIds[0], $"Retrieved user id {role.UserIds[0]} not the same as sample user id {inputModel.UserIds[0]}.");
            Assert.True(role.UserIds[1] == inputModel.UserIds[1], $"Retrieved user id {role.UserIds[1]} not the same as sample user id {inputModel.UserIds[1]}.");
            Assert.True(role.FunctionIds[0] == inputModel.FunctionIds[0], $"Retrieved function id {role.FunctionIds[0]} not the same as sample function id {inputModel.FunctionIds[0]}.");
            Assert.True(role.FunctionIds[1] == inputModel.FunctionIds[1], $"Retrieved function id {role.FunctionIds[1]} not the same as sample function id {inputModel.FunctionIds[1]}.");
        }
示例#6
0
        public async Task <Role> UpdateAsync(RoleSubmit roleSubmit, Guid updatedById)
        {
            // Start transactions to allow complete rollback in case of an error
            BeginAllTransactions();

            try
            {
                // Note: The mapper will only map the basic first level members of the RoleSubmit to the Role.
                // The RoleSubmit contains a list of User UUIDs that will need to be found and converted into actual user representations.
                RoleModel role = await roleRepository.GetByIdAsync(roleSubmit.Uuid);

                if (role == null)
                {
                    throw new ItemNotFoundException($"Role with ID '{roleSubmit.Uuid}' not found when attempting to update a role using this ID!");
                }

                if (role.Name != roleSubmit.Name)
                {
                    // Confirm the new name is available
                    var checkExistingNameModel = await roleRepository.GetByNameAsync(roleSubmit.Name);

                    if (checkExistingNameModel != null)
                    {
                        throw new ItemNotProcessableException($"Role with name '{roleSubmit.Name}' already exists.");
                    }
                }

                role.Name        = roleSubmit.Name;
                role.Description = roleSubmit.Description;
                role.ChangedBy   = updatedById;

                await AssignUsersToRoleFromUserIdList(role, roleSubmit.UserIds);
                await AssignFunctionsToRoleFromFunctionIdList(role, roleSubmit.FunctionIds);
                await AssignRolesToRoleFromRolesIdList(role, roleSubmit.RoleIds);

                // All successful
                CommitAllTransactions();

                return(mapper.Map <Role>(await roleRepository.UpdateAsync(role)));
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                RollbackAllTransactions();
                throw;
            }
        }
        public async Task CreateRoleAsync_WithTestRole_ReturnsCreatesdRole()
        {
            // Arrange
            var roleService = Substitute.For <IRoleService>();
            var inputModel  = new RoleSubmit()
            {
                Uuid        = Guid.NewGuid(),
                Name        = "Test Role Name",
                FunctionIds = new List <Guid>()
                {
                    new Guid(),
                    new Guid(),
                }
            };

            roleService.CreateAsync(inputModel, Arg.Any <Guid>())
            .Returns(new Role()
            {
                Uuid        = inputModel.Uuid,
                Name        = inputModel.Name,
                FunctionIds = inputModel.FunctionIds
            }
                     );

            var controller = new RoleController(roleService, orderByHelper, paginationHelper, mapper);

            // Act
            IActionResult actionResult = await controller.CreateRoleAsync(inputModel);

            // Assert
            var okResult = actionResult as OkObjectResult;

            Assert.NotNull(okResult);

            var role = okResult.Value as Role;

            Assert.NotNull(role);
            Assert.True(role.Uuid == inputModel.Uuid, $"Retrieved Id {role.Uuid} not the same as sample id {inputModel.Uuid}.");
            Assert.True(role.Name == inputModel.Name, $"Retrieved Name {role.Name} not the same as sample Name {inputModel.Name}.");
            Assert.True(role.FunctionIds[0] == inputModel.FunctionIds[0], $"Retrieved function id {role.FunctionIds[0]} not the same as sample function id {inputModel.FunctionIds[0]}.");
            Assert.True(role.FunctionIds[1] == inputModel.FunctionIds[1], $"Retrieved function id {role.FunctionIds[1]} not the same as sample function id {inputModel.FunctionIds[1]}.");
        }
示例#8
0
 public abstract Task <IActionResult> CreateRoleAsync([FromBody] RoleSubmit roleSubmit);
示例#9
0
 public abstract Task <IActionResult> UpdateRoleAsync([FromRoute][Required] Guid roleId, [FromBody] RoleSubmit roleSubmit);
示例#10
0
        public async override Task <IActionResult> UpdateRoleAsync([FromRoute, Required] Guid roleId, [FromBody] RoleSubmit roleSubmit)
        {
            if (roleId == Guid.Empty || roleSubmit.Uuid == Guid.Empty)
            {
                return(BadRequest());
            }

            var loggedOnUser = ClaimsHelper.GetScalarClaimValue <Guid>(User, ClaimTypes.NameIdentifier, Guid.Empty);

            return(Ok(await roleService.UpdateAsync(roleSubmit, loggedOnUser)));
        }
示例#11
0
        public async override Task <IActionResult> CreateRoleAsync([FromBody] RoleSubmit roleSubmit)
        {
            var loggedOnUser = ClaimsHelper.GetScalarClaimValue <Guid>(User, ClaimTypes.NameIdentifier, Guid.Empty);

            return(Ok(await roleService.CreateAsync(roleSubmit, loggedOnUser)));
        }
示例#12
0
        public RoleService_Tests()
        {
            var config = new MapperConfiguration(cfg =>
            {
                cfg.AddProfile(new RoleSubmitResourceRoleModelProfile());
                cfg.AddProfile(new RoleResourceRoleModelProfile());
            });

            mapper        = config.CreateMapper();
            roleGuid      = Guid.NewGuid();
            functionGuid  = Guid.NewGuid();
            childRoleGuid = Guid.NewGuid();

            mockedRoleModel = new RoleModel
            {
                Name = "Test Role",
                Id   = roleGuid
            };

            mockedRoleModel.RoleFunctions = new List <RoleFunctionModel>
            {
                new RoleFunctionModel
                {
                    Role     = mockedRoleModel,
                    Function = new FunctionModel
                    {
                        Id          = functionGuid,
                        Name        = "Test function model",
                        Description = "Test function description model"
                    }
                }
            };

            mockedRoleModel.ChildRoles = new List <RoleRoleModel>()
            {
                new RoleRoleModel()
                {
                    ChildRoleId  = childRoleGuid,
                    ParentRoleId = roleGuid,
                    ChildRole    = new RoleModel()
                    {
                        Id = childRoleGuid
                    },
                    ParentRole = mockedRoleModel
                }
            };

            mockedRoleSubmitModel = new RoleSubmit()
            {
                Uuid        = mockedRoleModel.Id,
                Name        = mockedRoleModel.Name,
                FunctionIds = new List <Guid>(),
                RoleIds     = new List <Guid>()
            };

            foreach (var function in mockedRoleModel.RoleFunctions)
            {
                mockedRoleSubmitModel.FunctionIds.Add(function.FunctionId);
            }

            foreach (var childRole in mockedRoleModel.ChildRoles)
            {
                mockedRoleSubmitModel.RoleIds.Add(childRole.ChildRoleId);
            }
        }