public void AddRole_ThrowException_If_Command_IsNotValid(string name, string description, Guid[] permissions)
        {
            var command = new AddRoleCommand(name, description, permissions);

            Assert.ThrowsAsync <BusinessException>(async() =>
                                                   await authorizationAppService.AddRole(command, CancellationToken.None));
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task <dynamic> AddRole(DTOAPIReq_Role data)
        {
            if (data.routes != null && data.routes.Count > 0)
            {
                //ensure pageRoutes is exist
                if (this.accesser.db.RoutePages.Where(x => data.routes.Contains(x.Id)).Count() != data.routes.Count)
                {
                    return(-1);
                }
            }


            var routes = data.routes.Select(x => new DTOIn_PageRouteId {
                PageRouteID = x
            }).ToArray();

            long NewID = this.IDGenerator.GetNewID <Role>();
            var  cmd   = new AddRoleCommand
            {
                key         = NewID,
                description = data.description,
                name        = data.name,
                routes      = routes
            };

            await this.publishEndpoint.Publish(cmd);

            return(NewID);
        }
        public async Task <Guid> AddRole(AddRoleCommand command, CancellationToken cancellationToken)
        {
            if (command == null)
            {
                throw new ArgumentNullException(nameof(command));
            }

            command.EnsureIsValid();

            var persistedRole = await authorizationRepository.GetRoleByName(command.Name, cancellationToken).ConfigureAwait(false);

            if (persistedRole is not null)
            {
                throw new BusinessException(Messages.RoleAlreadyExist);
            }

            var role = new Role()
            {
                Name        = command.Name,
                Description = command.Description
            };

            await authorizationRepository.AddRole(role, cancellationToken).ConfigureAwait(false);

            return(role.Id);
        }
示例#4
0
        /// <summary>
        /// Creates a valid <see cref="AddRoleCommand"/>.
        /// </summary>
        /// <param name="uniqueData">Unique data to use in the "Title" property.</param>
        /// <param name="userAreaCode">User area to assign the role to.</param>
        /// <param name="permissionInitializer">
        /// A filter function to indicate which permissions to add. If this is <see langword="null"/>
        /// then all permissions are added. This is the equivalent of an <see cref="IRoleInitializer"/>.
        /// </param>
        public AddRoleCommand CreateAddCommand(string uniqueData, string userAreaCode, Func <IEnumerable <IPermission>, IEnumerable <IPermission> > permissionInitializer = null)
        {
            var command = new AddRoleCommand()
            {
                Title        = uniqueData,
                UserAreaCode = userAreaCode
            };

            var permissions = _permissionRepository.GetAll();

            if (permissionInitializer != null)
            {
                permissions = permissionInitializer(permissions);
            }

            command.Permissions = permissions
                                  .Select(p => new PermissionCommandData()
            {
                EntityDefinitionCode = (p as IEntityPermission)?.EntityDefinition.EntityDefinitionCode,
                PermissionCode       = p.PermissionType.Code
            })
                                  .ToList();

            return(command);
        }
示例#5
0
        public async Task Fails_when_group_is_missing() => await Run(async sut =>
        {
            var command = new AddRoleCommand(Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), "role1");

            Func <Task> action = async() => await sut.SendAsync(command);

            await action.Should().ThrowAsync <GroupNotFoundException>();
        });
示例#6
0
 private void NewUser_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
 {
     StartCreateNewCommand.RaiseCanExecuteChanged();
     AddRoleCommand.RaiseCanExecuteChanged();
     RemoveRoleCommand.RaiseCanExecuteChanged();
     AddRolesCommand.RaiseCanExecuteChanged();
     RemoveRolesCommand.RaiseCanExecuteChanged();
     AddMultipleRolesCommand.RaiseCanExecuteChanged();
 }
示例#7
0
        public async Task AddRole(AddRoleCommand addRoleCommand, Contexts contexts)
        {
            if (!addRoleCommand.Roles.Any())
            {
                throw new NotEnoughArgumentsException();
            }
            var safeRoles = this._queryBus.Execute(new GetDiscordServerSafeRolesQuery(contexts.Server.Id)).SafeRoles;

            await this._rolesService.AddRoleToUser(safeRoles, contexts, addRoleCommand.Roles);
        }
示例#8
0
        public Task AddRole(AddRoleCommand addRoleCommand, Contexts contexts)
        {
            if (addRoleCommand.Roles.Count > 5)
            {
                throw new InvalidArgumentsException();
            }
            var safeRoles = this._queryBus.Execute(new GetDiscordServerSafeRolesQuery(contexts.Server.Id)).SafeRoles;

            return(this._rolesService.AddRoleToUser(safeRoles, contexts, addRoleCommand.Roles));
        }
示例#9
0
 void UpateCommands()
 {
     AvailableToCurrentRoleCommand.RaiseCanExecuteChanged();
     CurrentToAvailableRoleCommand.RaiseCanExecuteChanged();
     AddMultipleRolesCommand.RaiseCanExecuteChanged();
     StarEditUserCommand.RaiseCanExecuteChanged();
     DeleteUserCommand.RaiseCanExecuteChanged();
     AddRoleCommand.RaiseCanExecuteChanged();
     RemoveRoleCommand.RaiseCanExecuteChanged();
 }
示例#10
0
        public async Task <IActionResult> AddRole([FromBody] AddRoleCommand command)
        {
            if (!HttpContext.Request.Headers.TryGetValue("Requesting-ProductId", out var productId))
            {
                return(StatusCode(500));
            }

            command.ProductId = Guid.Parse(productId);

            return(Ok(await mediator.Send(command).ConfigureAwait(false)));
        }
示例#11
0
        public async Task Fails_when_role_name_is_invalid(string roleName) => await Run(async sut =>
        {
            var group = await GroupBuilder.For(sut)
                        .CreateGroup("group1").AsOwner().CreateRole("role1").Build().Build().Build();

            var command = new AddRoleCommand(group.OwnerId, group.GroupId, group.Role(1).RoleId, roleName);

            Func <Task> action = async() => await sut.SendAsync(command);

            await action.Should().ThrowAsync <InvalidRoleNameException>();
        });
示例#12
0
 public ActionResult AddRole()
 {
     if (Profile != null)
     {
         var            name    = RequestString("Name");
         AddRoleCommand command = new AddRoleCommand(name, -1, 1);
         CommandBus.Instance.Send(command);
         return(new ActionResult(command.Result.Status, new { ID = command.Id }, null, command.Result.Msg));
     }
     return(new ActionResult(false, null, null, "无权操作,你的IP我们已经记录!"));
 }
        public async Task <ActionResult <Role> > Create(AddRoleCommand addRoleCommand)
        {
            try
            {
                Role role = await this.mediator.Send(addRoleCommand);

                return(Ok(role));
            }
            catch (Exception ex)
            {
                return(this.BadRequest(ex));
            }
        }
示例#14
0
        public async Task AddAsync(AddRoleCommand command)
        {
            command.Name = command.Name.ToLower();

            var role = await _repository.GetAsync(command.Name);

            if (!(role is null))
            {
                throw new RoleException($"Role name: {command.Name} exist.");
            }

            await _repository.AddAsync(new Role { Name = command.Name });
        }
示例#15
0
 public ResultDto CreateRole(RoleDto newRole)
 {
     return(Result(() =>
     {
         var command = new AddRoleCommand
         {
             Name = newRole.Name,
             RoleType = newRole.RoleType,
             Description = newRole.Description,
         };
         CommandDispatcher.Send(command);
     }));
 }
        public async Task AddRole()
        {
            var command = new AddRoleCommand("Admin", "Allow Admin users", null);

            authorizationRepositoryMock.GetRoleByName(command.Name, Arg.Any <CancellationToken>())
            .Returns(default(Role));

            var roleId = await authorizationAppService.AddRole(command, CancellationToken.None);

            Assert.IsNotNull(roleId);
            Assert.IsFalse(roleId == Guid.Empty);

            await authorizationRepositoryMock.Received(1).GetRoleByName(command.Name, Arg.Any <CancellationToken>());

            await authorizationRepositoryMock.Received(1).AddRole(Arg.Any <Role>(), Arg.Any <CancellationToken>());
        }
        public async Task AddRole_Throw_Exception_If_Role_Already_Exist()
        {
            var expectedRole = new Role()
            {
                Name = "Admin", Description = "Allow Admin users"
            };

            var command = new AddRoleCommand("Admin", "Allow Admin users", null);

            authorizationRepositoryMock.GetRoleByName(command.Name, Arg.Any <CancellationToken>())
            .Returns(expectedRole);

            Assert.ThrowsAsync <BusinessException>(async() =>
                                                   await authorizationAppService.AddRole(command, CancellationToken.None), "Role already exist.");

            await authorizationRepositoryMock.Received(1).GetRoleByName(command.Name, Arg.Any <CancellationToken>());
        }
示例#18
0
        public async Task Added_role_has_the_lowest_priority_after_the_everyone_role() => await Run(async sut =>
        {
            var group = await GroupBuilder.For(sut).CreateGroup("group1")
                        .AsOwner()
                        .CreateRole("role1").Build()
                        .CreateRole("role2").Build()
                        .Build().Build();
            var addRole3 = new AddRoleCommand(group.OwnerId, group.GroupId, Guid.NewGuid(), "role3");

            await sut.SendAsync(addRole3);

            var roles = await sut.QueryAsync(new GetRolesQuery(group.OwnerId, group.GroupId));
            roles.Should().SatisfyRespectively(
                x =>
            {
                x.RoleId.Should().Be(group.Role(1).RoleId);
                x.Priority.Should().Be(2);
                x.Name.Should().Be(group.Role(1).Name);
            },
                x =>
            {
                x.RoleId.Should().Be(group.Role(2).RoleId);
                x.Priority.Should().Be(1);
                x.Name.Should().Be(group.Role(2).Name);
            },
                x =>
            {
                x.RoleId.Should().Be(addRole3.RoleId);
                x.Priority.Should().Be(0);
                x.Name.Should().Be(addRole3.Name);
            },
                x =>
            {
                x.RoleId.Should().NotBeEmpty();
                x.Priority.Should().Be(-1);
                x.Name.Should().Be("@everyone");
            }
                );
        });
        public ActionResult AddRole([FromBody] RoleRequest request)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(request.Email))
                {
                    throw new ArgumentNullException("Email is empty");
                }

                var addRoleCommand = new AddRoleCommand(request, NameConstants.AuthenticationServiceAddRoleCommand);
                if (!_commandPublisher.Publish <bool>(addRoleCommand).Result)
                {
                    throw new ApplicationException("Assigning role has failed!");
                }
            }
            catch (Exception)
            {
                return(BadRequest());
            }

            return(Ok());
        }
示例#20
0
        public bool AddRole(AddRoleCommand request)
        {
            var roleRequest = request.RoleRequest;

            try
            {
                var user = _credentialDataMapper.Find(x => x.Email.ToLower().CompareTo(roleRequest.Email.ToLower()) == 0).FirstOrDefault();
                if (user == null)
                {
                    throw new NullReferenceException("Email not found in the database");
                }
                else
                {
                    user.CredentialRoles.Add(new CredentialRoleEntity()
                    {
                        Credential = user,
                        Role       = new RoleEntity()
                        {
                            Name            = roleRequest.Role.ToString(),
                            CredentialRoles = new HashSet <CredentialRoleEntity>()
                        }
                    });

                    _credentialDataMapper.Update(user);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError("DB exception occured with email: {0}", roleRequest?.Email);
                _logger.LogDebug(
                    "DB exception occured with email {}, it threw exception: {}. Inner exception: {}",
                    roleRequest?.Email, ex.Message, ex.InnerException?.Message
                    );

                throw new DatabaseException("Something unexpected happened while updating in the database");
            }

            return(true);
        }
        public async Task <int> AddAsync(AddRoleCommand command)
        {
            await ExtendableContentRepository.ExecuteCommandAsync(command);

            return(command.OutputRoleId);
        }
示例#22
0
 public void Handle(AddRoleCommand message)
 {
     this.Handle(message.AcSession, message.Input, true);
 }
示例#23
0
        public async Task <IActionResult> Add(AddRoleCommand command, CancellationToken cancellationToken = default)
        {
            var roleId = await authorizationAppService.AddRole(command, cancellationToken);

            return(Ok(roleId));
        }
示例#24
0
        public async Task <IActionResult> Add([FromBody] AddRoleCommand command)
        {
            await _roleService.AddAsync(command);

            return(Ok());
        }
示例#25
0
 public IResponseResult AddRole([FromBody] AddRoleCommand command) => command.Execute(param: this._roleparam);
示例#26
0
 public Task <JsonResult> Post([FromBody] AddRoleCommand command)
 {
     return(_apiResponseHelper.RunCommandAsync(command));
 }
示例#27
0
 public async Task <IActionResult> Post([FromBody] AddRoleCommand command)
 {
     return(await _apiResponseHelper.RunCommandAsync(this, command));
 }
示例#28
0
        public async Task AddRole(AddRoleCommand addRoleCommand, Contexts contexts)
        {
            var safeRoles = this._queryBus.Execute(new GetDiscordServerSafeRolesQuery(contexts.Server.Id)).SafeRoles;

            await this._rolesService.AddRoleToUser(safeRoles, contexts, addRoleCommand.Roles);
        }