Exemplo n.º 1
0
        public async Task <string> Handle(DeleteUserCommand request, CancellationToken cancellationToken)
        {
            var user = await _userRepository.FindByIdAsync(new UserId(request.UserId));

            if (user is null)
            {
                throw new NotFoundException(request.UserId.ToString(), "User");
            }
            if (user.Rights.Any(r => r.Name == RightEnum.Admin))
            {
                var adminRight = await _readRightRepository.GetOneRightNavigationByName(RightEnum.Admin);

                if (adminRight is null)
                {
                    throw new NotFoundException(RightEnum.Admin.ToString(), "Right");
                }

                var adminUsers = await _readUserRepository.FindAllPublicUsers(new GetPublicUsersQuery()
                {
                    RightIdFilter = adminRight.Id
                });

                if (adminUsers.Count <= 1)
                {
                    throw new ApplicationException("Cannot delete last existing admin");
                }
            }
            await _userRepository.RemoveAsync(user.Id);

            return(user.Id.ToString());
        }
Exemplo n.º 2
0
        public async Task <string> Handle(ChangeUserRightsCommand request, CancellationToken cancellationToken)
        {
            var user = await _userRepository.FindByIdAsync(new UserId(request.UserId));

            var rights = new List <RightNavigation>();

            foreach (var rightId in request.RightsIds)
            {
                var right = await _rightsRepository.GetOneRightNavigationById(rightId);

                if (right is null)
                {
                    throw new NotFoundException(rightId.ToString(), "Right");
                }
                rights.Add(right);
            }

            if (user is null)
            {
                throw new NotFoundException(_currentUserService.UserId.Value.ToString(), "user");
            }
            if (user.Rights.Any(r => r.Name == RightEnum.Admin) && rights.All(r => r.Name != RightEnum.Admin))
            {
                var adminRight = await _rightsRepository.GetOneRightNavigationByName(RightEnum.Admin);

                if (adminRight is null)
                {
                    throw new NotFoundException(RightEnum.Admin.ToString(), "Right");
                }

                var adminUsers = await _readUserRepository.FindAllPublicUsers(new GetPublicUsersQuery()
                {
                    RightIdFilter = adminRight.Id
                });

                if (adminUsers.Count <= 1)
                {
                    throw new ApplicationException("Cannot remove user admin right if user is the last admin");
                }
            }

            user.SetRights(rights.Select(r => new Right(r.Name)).ToList());
            await _userRepository.SetAsync(user);

            return(user.Id.ToString());
        }