Esempio n. 1
0
        public async Task <GuestInvite> UpdateGuestInviteAsync(GuestInvite guestInviteModel)
        {
            var guestInviteIdValidationResult = _validatorLocator.Validate <GuestInviteIdValidator>(guestInviteModel.Id);
            var guestInviteValidationResult   = _validatorLocator.Validate <GuestInviteValidator>(guestInviteModel);
            var errors = new List <ValidationFailure>();

            if (!guestInviteIdValidationResult.IsValid)
            {
                errors.AddRange(guestInviteIdValidationResult.Errors);
            }

            if (!guestInviteValidationResult.IsValid)
            {
                errors.AddRange(guestInviteValidationResult.Errors);
            }

            if (errors.Any())
            {
                _logger.Error("Failed to validate the resource id and/or resource while attempting to update a GuestInvite resource.");
                throw new ValidationFailedException(errors);
            }

            var result = await _guestInviteRepository.UpdateItemAsync(guestInviteModel.Id, guestInviteModel);

            _eventService.Publish(EventNames.GuestInviteUpdated, result);

            return(result);
        }
        public async Task GetGuestInvitesByUserIdAsyncGetsItems()
        {
            var userId  = Guid.NewGuid();
            var invites = new List <GuestInvite> {
                GuestInvite.Example(), GuestInvite.Example(), GuestInvite.Example()
            };
            var moreInvites = new List <GuestInvite> {
                GuestInvite.Example(), GuestInvite.Example(), GuestInvite.Example()
            };

            invites.ForEach(w => w.UserId = userId);
            invites.AddRange(moreInvites);

            var request = GetGuestInvitesRequest.Example();

            request.GuestUserId = userId;
            request.GuestEmail  = "*****@*****.**";

            _guestInviteRepositoryMock.Setup(m => m.GetItemsAsync(It.IsAny <Expression <Func <GuestInvite, bool> > >(), It.IsAny <BatchOptions>(), It.IsAny <CancellationToken>()))
            .Returns <Expression <Func <GuestInvite, bool> >, BatchOptions, CancellationToken>((predicate, o, c) =>
            {
                var expression = predicate.Compile();
                IEnumerable <GuestInvite> sublist = invites.Where(expression).ToList();
                return(Task.FromResult(sublist));
            });

            var result = await _target.GetGuestInvitesForUserAsync(request);

            Assert.True(result != null && result.Count() == invites.Count - moreInvites.Count);
        }
        public async Task GetGuestInviteByProjectIdReturnsOk()
        {
            _guestInviteControllerMock
            .Setup(x => x.GetValidGuestInvitesByProjectIdAsync(It.IsAny <Guid>()))
            .ReturnsAsync(new List <GuestInvite> {
                GuestInvite.Example()
            });

            var response = await UserTokenBrowser.Get($"{Routing.ProjectsRoute}/{Guid.NewGuid()}/{Routing.GuestInvitesPath}", BuildRequest);

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
        }
        public async Task GetGuestInviteByUserIdReturnsOk()
        {
            _guestInviteControllerMock
            .Setup(x => x.GetGuestInvitesForUserAsync(It.IsAny <GetGuestInvitesRequest>()))
            .ReturnsAsync(new List <GuestInvite> {
                GuestInvite.Example()
            });

            var response = await UserTokenBrowser.Post($"{Routing.UsersRoute}/{Routing.GuestInvitesPath}", BuildRequest);

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
        }
Esempio n. 5
0
        public async Task <GuestInvite> CreateGuestInviteAsync(GuestInvite model)
        {
            var validationResult = _validatorLocator.Validate <GuestInviteValidator>(model);

            if (!validationResult.IsValid)
            {
                throw new ValidationFailedException(validationResult.Errors);
            }

            // Get dependent resources
            var projectTask       = GetProjectAsync(model.ProjectId);
            var invitedByUserTask = GetUserAsync(model.InvitedBy);
            await Task.WhenAll(projectTask, invitedByUserTask);

            var project       = projectTask.Result;
            var invitedByUser = invitedByUserTask.Result;

            var accessCode = await GetGuestAccessCodeAsync(project);

            model.Id = model.Id == Guid.Empty ? Guid.NewGuid() : model.Id;
            model.CreatedDateTime   = DateTime.UtcNow;
            model.ProjectAccessCode = accessCode;
            model.ProjectTenantId   = project.TenantId;

            var result = await _guestInviteRepository.CreateItemAsync(model);

            // Delete all prior guest invites with the same email and ProjectId as the session just created.
            await _guestInviteRepository.DeleteItemsAsync(x => x.ProjectId == model.ProjectId &&
                                                          x.GuestEmail == model.GuestEmail &&
                                                          x.Id != result.Id);

            _eventService.Publish(EventNames.GuestInviteCreated, result);

            // Send an invite email to the guest
            var emailResult = await _emailSendingService.SendGuestInviteEmailAsync(project.Name, project.ProjectUri, model.GuestEmail, invitedByUser.FirstName);

            if (!emailResult.IsSuccess())
            {
                _logger.Error($"Sending guest invite email failed. Reason={emailResult.ReasonPhrase} Error={_serializer.SerializeToString(emailResult.ErrorResponse)}");
                await _guestInviteRepository.DeleteItemAsync(result.Id);
            }

            return(result);
        }
        private List <GuestInvite> MakeTestInviteList(Guid projectId,
                                                      string email,
                                                      int matchingProjectIdEmailAccessCodeCount,
                                                      int matchingProjectIdAccessCodeCount,
                                                      int matchingProjectIdEmailCount,
                                                      int nonMatchingProjectCount)
        {
            var invites = new List <GuestInvite>();

            Repeat(matchingProjectIdEmailAccessCodeCount, () =>
            {
                var invite               = GuestInvite.Example();
                invite.ProjectId         = projectId;
                invite.GuestEmail        = email;
                invite.ProjectAccessCode = _defaultProject.GuestAccessCode;
                invite.CreatedDateTime   = DateTime.UtcNow;
                invites.Add(invite);
            });

            for (var i = 0; i < matchingProjectIdAccessCodeCount; i++)
            {
                var invite = GuestInvite.Example();
                invite.ProjectId         = projectId;
                invite.ProjectAccessCode = _defaultProject.GuestAccessCode;
                invite.GuestEmail        = i + email;
                invites.Add(invite);
            }

            Repeat(matchingProjectIdEmailCount, () =>
            {
                var invite        = GuestInvite.Example();
                invite.ProjectId  = projectId;
                invite.GuestEmail = email;
                invites.Add(invite);
            });

            Repeat(nonMatchingProjectCount, () => { invites.Add(GuestInvite.Example()); });

            return(invites);
        }
        public GuestInviteControllerTests()
        {
            var repositoryFactoryMock = new Mock <IRepositoryFactory>();

            _guestInviteRepositoryMock = new Mock <IRepository <GuestInvite> >();
            _defaultGuestInvite        = new GuestInvite
            {
                Id              = Guid.NewGuid(),
                InvitedBy       = Guid.NewGuid(),
                ProjectId       = Guid.NewGuid(),
                CreatedDateTime = DateTime.UtcNow
            };

            _defaultProject = new Project
            {
                Id = Guid.NewGuid(),
                GuestAccessCode    = Guid.NewGuid().ToString(),
                IsGuestModeEnabled = true
            };

            _userApiMock.Setup(x => x.GetUserAsync(It.IsAny <Guid>()))
            .ReturnsAsync(MicroserviceResponse.Create(HttpStatusCode.OK, User.GuestUserExample()));

            _projectApiMock.Setup(x => x.GetProjectByIdAsync(It.IsAny <Guid>(), null))
            .ReturnsAsync(MicroserviceResponse.Create(HttpStatusCode.OK, Project.Example()));

            _projectApiMock.Setup(x => x.ResetGuestAccessCodeAsync(It.IsAny <Guid>(), null))
            .ReturnsAsync(MicroserviceResponse.Create(HttpStatusCode.OK, Project.Example()));

            _emailServiceMock.Setup(x => x.SendGuestInviteEmailAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>()))
            .ReturnsAsync(MicroserviceResponse.Create(HttpStatusCode.OK));

            _guestInviteRepositoryMock
            .Setup(x => x.GetItemAsync(It.IsAny <Guid>(), It.IsAny <BatchOptions>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(_defaultGuestInvite);

            _guestInviteRepositoryMock
            .Setup(x => x.CreateItemAsync(It.IsAny <GuestInvite>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync((GuestInvite guestInvite, CancellationToken c) => guestInvite);

            _guestInviteRepositoryMock
            .Setup(x => x.UpdateItemAsync(_defaultGuestInvite.Id, It.IsAny <GuestInvite>(), It.IsAny <UpdateOptions>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync((Guid id, GuestInvite guestInvite, UpdateOptions o, CancellationToken c) => guestInvite);

            repositoryFactoryMock
            .Setup(x => x.CreateRepository <GuestInvite>())
            .Returns(_guestInviteRepositoryMock.Object);

            _validatorMock
            .Setup(v => v.ValidateAsync(It.IsAny <object>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(new ValidationResult());

            _validatorMock
            .Setup(v => v.Validate(It.IsAny <object>()))
            .Returns(new ValidationResult());

            _validatorLocator
            .Setup(g => g.GetValidator(It.IsAny <Type>()))
            .Returns(_validatorMock.Object);

            var loggerFactoryMock = new Mock <ILoggerFactory>();

            loggerFactoryMock
            .Setup(x => x.Get(It.IsAny <LogTopic>()))
            .Returns(new Mock <ILogger>().Object);

            _target = new GuestInviteController(_userApiMock.Object, _projectApiMock.Object, _emailServiceMock.Object, repositoryFactoryMock.Object, _validatorLocator.Object, _eventServiceMock.Object, loggerFactoryMock.Object, _serializerMock.Object);
        }