Beispiel #1
0
        [InlineData(Email, "PASSWORD", false)]          // Password casing
        public async Task Authenticate_GivenCredentials_VerifiesPasswordAndEmail(string email, string password, bool shouldWork)
        {
            GetDatabaseContext getContext = ContextUtilities.CreateInMemoryContext(_output);

            // Arrange
            using (IDatabaseContext context = getContext())
            {
                EntityEntry <User> userEntry = context.Users.Add(ContextUtilities.CreateJohnDoe());

                userEntry.Entity.Email        = Email;
                userEntry.Entity.PasswordHash = PasswordHash;

                await context.SaveChangesAsync();
            }

            // Act
            var passwordServiceMock = new Mock <IPasswordService>();

            passwordServiceMock.Setup(p => p.NeedsRehash(PasswordHash)).Returns(false);
            passwordServiceMock.Setup(p => p.VerifyPassword(Password, PasswordHash)).Returns(true);

            var authenticationService = new AuthenticationService(passwordServiceMock.Object, getContext, DummyLogger <AuthenticationService>());

            (bool isAuthenticated, _) = await authenticationService.AuthenticateAsync(email, password);

            // Assert
            passwordServiceMock.Verify(p => p.VerifyPassword(password, PasswordHash), Times.AtMostOnce);
            if (shouldWork)
            {
                passwordServiceMock.Verify(p => p.NeedsRehash(PasswordHash), Times.Once);
            }

            Assert.Equal(shouldWork, isAuthenticated);
        }
Beispiel #2
0
        public async Task SetNewUserData_GivenValidData_UserUpdated()
        {
            GetDatabaseContext getContext = ContextUtilities.CreateInMemoryContext(_output);
            int          johnId;
            const string NewName = "New Fancy Name";
            const string NewMail = "*****@*****.**";

            // Arrange
            using (IDatabaseContext context = getContext())
            {
                User john = context.Users.Add(ContextUtilities.CreateJohnDoe()).Entity;

                await context.SaveChangesAsync();

                johnId = john.Id;
            }

            // Act
            (UserController controller, _, _, _) = CreateController(getContext, johnId);

            IActionResult response = await controller.SetNewUserData(new SetUserDataDto { NewEmail = NewMail, NewFullName = NewName });

            // Assert
            Assert.IsType <OkResult>(response);
            using (IDatabaseContext context = getContext())
            {
                User loadedUser = context.Users.Single();
                Assert.Equal(NewName, loadedUser.FullName);
                Assert.Equal(NewMail, loadedUser.Email);
            }
        }
        public async Task JoinEvent_GivenPrivateEvent_OrganizerCanJoin()
        {
            GetDatabaseContext getContext = ContextUtilities.CreateInMemoryContext(_output);
            int organizerId;
            int eventId;

            // Arrange
            using (IDatabaseContext context = getContext())
            {
                Event @event = DummyEvent(ContextUtilities.CreateJohnDoe(), true);
                context.Events.Add(@event);

                await context.SaveChangesAsync();

                organizerId = @event.OrganizerId;
                eventId     = @event.Id;
            }

            // Act
            (ParticipateEventController participateEventController, _) = CreateController(getContext, organizerId);

            IActionResult response = await participateEventController.JoinEvent(new JoinEventDto
            {
                EventId = eventId
            });

            // Assert
            Assert.IsType <OkResult>(response);
        }
        public async Task Register_GivenExistingEmail_UserNotRegistered()
        {
            GetDatabaseContext getContext = ContextUtilities.CreateInMemoryContext(_output);

            // Arrange
            var data = new RegisterDto {
                Email = "*****@*****.**", FullName = "New User", Password = "******"
            };

            using (IDatabaseContext context = getContext())
            {
                context.Users.Add(new User
                {
                    Email        = data.Email,
                    FullName     = "Some other name",
                    PasswordHash = "Some hashed password"
                });

                await context.SaveChangesAsync();
            }

            // Act
            (UserController controller, _, _, _) = CreateController(getContext, null);
            IActionResult response = await controller.Register(data);

            // Assert
            Assert.IsType <BadRequestObjectResult>(response);
            var objectResult = (BadRequestObjectResult)response;

            Assert.Equal(RequestStringMessages.EmailAlreadyInUse, objectResult.Value);
        }
        public async Task DeleteEvent_GivenNonExistingEvent_ErrorReturned()
        {
            GetDatabaseContext getContext = ContextUtilities.CreateInMemoryContext(_output);
            int johnDoeId;
            int eventId;

            // Arrange
            using (IDatabaseContext context = getContext())
            {
                User john    = ContextUtilities.CreateJohnDoe();
                User richard = ContextUtilities.CreateRichardRoe();

                Event @event = DummyEvent(richard, true);

                await context.SaveChangesAsync();

                johnDoeId = john.Id;
                eventId   = @event.Id;
            }

            // Act
            (OrganizeEventController controller, _) = CreateController(getContext, johnDoeId);

            IActionResult response = await controller.DeleteEvent(eventId);

            // Assert
            Assert.IsType <BadRequestObjectResult>(response);
            var objectResult = (BadRequestObjectResult)response;

            Assert.Equal(RequestStringMessages.EventNotFound, objectResult.Value);
        }
        public async Task GetDetails_GivenPublicEvent_DetailsReturned()
        {
            GetDatabaseContext getContext = ContextUtilities.CreateInMemoryContext(_output);
            int publicEventId;
            int johnId;

            // Arrange
            using (IDatabaseContext context = getContext())
            {
                EntityEntry <User> john = context.Users.Add(ContextUtilities.CreateJohnDoe());
                User  richard           = ContextUtilities.CreateRichardRoe();
                Event publicEvent       = DummyEvent(richard);
                context.Events.Add(publicEvent);

                await context.SaveChangesAsync();

                publicEventId = publicEvent.Id;
                johnId        = john.Entity.Id;
            }

            // Act
            (ParticipateEventController participateEventController, _) = CreateController(getContext, johnId);

            IActionResult response = await participateEventController.GetDetails(publicEventId);

            // Assert
            Assert.IsType <OkObjectResult>(response);
        }
        public async Task JoinEvent_GivenPrivateEvent_UserCanNotJoin()
        {
            GetDatabaseContext getContext = ContextUtilities.CreateInMemoryContext(_output);
            int johnDoeId;
            int eventId;

            // Arrange
            using (IDatabaseContext context = getContext())
            {
                EntityEntry <User> john = context.Users.Add(ContextUtilities.CreateJohnDoe());

                Event privateEvent = DummyEvent(ContextUtilities.CreateRichardRoe(), true);
                context.Events.Add(privateEvent);

                await context.SaveChangesAsync();

                johnDoeId = john.Entity.Id;
                eventId   = privateEvent.Id;
            }

            // Act
            (ParticipateEventController participateEventController, _) = CreateController(getContext, johnDoeId);

            IActionResult response = await participateEventController.JoinEvent(new JoinEventDto
            {
                EventId = eventId
            });

            // Assert
            Assert.IsType <BadRequestObjectResult>(response);
            var objectResult = (BadRequestObjectResult)response;

            Assert.Equal(RequestStringMessages.InvitationRequired, objectResult.Value);
        }
Beispiel #8
0
        private (GetDatabaseContext, SessionService) SetupSessionService()
        {
            GetDatabaseContext getContext = ContextUtilities.CreateInMemoryContext(_output);
            var sessionService            = new SessionService(_configuration, getContext, DummyLogger <SessionService>());

            return(getContext, sessionService);
        }
Beispiel #9
0
        public async Task DeleteAccount_GivenSimpleUser_UserDeleted()
        {
            GetDatabaseContext getContext = ContextUtilities.CreateInMemoryContext(_output);
            int johnDoeId;

            // Arrange
            using (IDatabaseContext context = getContext())
            {
                EntityEntry <User> john = context.Users.Add(ContextUtilities.CreateJohnDoe());

                await context.SaveChangesAsync();

                johnDoeId = john.Entity.Id;
            }

            // Act
            (UserController controller, _, _, _) = CreateController(getContext, johnDoeId);
            IActionResult response = await controller.DeleteAccount();

            // Assert
            Assert.IsType <OkResult>(response);
            using (IDatabaseContext context = getContext())
            {
                Assert.Empty(context.Users);
            }
        }
        public async Task GetChatMessage_GivenNotParticipatingUser_ErrorReturned()
        {
            GetDatabaseContext getContext = ContextUtilities.CreateInMemoryContext(_output);
            int johnDoeId;
            int eventId;

            // Arrange
            using (IDatabaseContext context = getContext())
            {
                EntityEntry <User> john = context.Users.Add(ContextUtilities.CreateJohnDoe());

                Event privateEvent = DummyEvent(john.Entity);
                context.Events.Add(privateEvent);

                await context.SaveChangesAsync();

                johnDoeId = john.Entity.Id;
                eventId   = privateEvent.Id;
            }

            // Act
            (EventChatController eventChatController, _) = CreateController(getContext, johnDoeId);

            IActionResult response = await eventChatController.GetChatMessages(new GetChatMessagesDto { EventId = eventId });

            // Assert
            Assert.IsType <BadRequestObjectResult>(response);
            var objectResult = (BadRequestObjectResult)response;

            Assert.Equal(RequestStringMessages.UserNotPartOfEvent, objectResult.Value);
        }
        public async Task ConfigureNotifications_GivenNonexistentEvent_ErrorReturned()
        {
            GetDatabaseContext getContext = ContextUtilities.CreateInMemoryContext(_output);
            int johnId;

            // Arrange
            using (IDatabaseContext context = getContext())
            {
                EntityEntry <User> john = context.Users.Add(ContextUtilities.CreateJohnDoe());

                await context.SaveChangesAsync();

                johnId = john.Entity.Id;
            }

            // Act
            (ParticipateEventController participateEventController, _) = CreateController(getContext, johnId);

            IActionResult response = await participateEventController.ConfigureNotifications(new NotificationConfigurationDto { EventId = 42, SendReminderEmail = true, SendSummaryEmail = true, SendLastMinuteChangesEmail = true });

            // Assert
            Assert.IsType <BadRequestObjectResult>(response);
            var objectResult = (BadRequestObjectResult)response;

            Assert.Equal(RequestStringMessages.UserNotPartOfEvent, objectResult.Value);
        }
Beispiel #12
0
        public async Task SetNewUserData_GivenAlreadyUsedEmail_ErrorReturned()
        {
            GetDatabaseContext getContext = ContextUtilities.CreateInMemoryContext(_output);
            int          johnId;
            const string NewName = "New Fancy Name";
            string       usedEmail;

            // Arrange
            using (IDatabaseContext context = getContext())
            {
                User john = context.Users.Add(ContextUtilities.CreateJohnDoe()).Entity;

                User richard = context.Users.Add(ContextUtilities.CreateRichardRoe()).Entity;
                usedEmail = richard.Email;

                await context.SaveChangesAsync();

                johnId = john.Id;
            }

            // Act
            (UserController controller, _, _, _) = CreateController(getContext, johnId);

            IActionResult response = await controller.SetNewUserData(new SetUserDataDto { NewEmail = usedEmail, NewFullName = NewName });

            // Assert
            Assert.IsType <BadRequestObjectResult>(response);
            var objectResult = (BadRequestObjectResult)response;

            Assert.Equal(RequestStringMessages.EmailAlreadyInUse, objectResult.Value);
        }
Beispiel #13
0
        public async Task SetNewPassword_GivenWrongCurrentPassword_DoesNotChangePassword()
        {
            GetDatabaseContext getContext = ContextUtilities.CreateInMemoryContext(_output);
            User         john;
            const string WrongCurrentPassword = "******";

            // Arrange
            using (IDatabaseContext context = getContext())
            {
                john = context.Users.Add(ContextUtilities.CreateJohnDoe()).Entity;

                await context.SaveChangesAsync();
            }

            // Act
            (UserController controller, _, Mock <IPasswordService> passwordServiceMock, _) = CreateController(getContext, john.Id);
            passwordServiceMock.Setup(p => p.VerifyPassword(WrongCurrentPassword, john.PasswordHash)).Returns(false);

            IActionResult response = await controller.SetNewPassword(new SetPasswordDto { CurrentPassword = WrongCurrentPassword, NewPassword = "******" });

            // Assert
            Assert.IsType <BadRequestObjectResult>(response);
            var objectResult = (BadRequestObjectResult)response;

            Assert.Equal(RequestStringMessages.CurrentPasswordWrong, objectResult.Value);
        }
        public async Task ResetPassword_GivenUsedPasswordReset_RequestRejected()
        {
            GetDatabaseContext getContext = ContextUtilities.CreateInMemoryContext(_output);
            Guid resetToken;

            // Arrange
            using (IDatabaseContext context = getContext())
            {
                User john  = ContextUtilities.CreateJohnDoe();
                var  reset = new PasswordReset {
                    Requested = DateTime.UtcNow, User = john, Used = true
                };
                context.PasswordResets.Add(reset);

                await context.SaveChangesAsync();

                resetToken = reset.Token;
            }

            // Act
            (ResetPasswordController controller, _, _) = CreateController(getContext, null);

            IActionResult response = await controller.ResetPassword(new ResetPasswordDto { NewPassword = "******", PasswordResetToken = resetToken });

            // Assert
            Assert.IsType <BadRequestObjectResult>(response);
            var badRequestResponse = (BadRequestObjectResult)response;

            Assert.Equal(RequestStringMessages.ResetCodeAlreadyUsedOrExpired, badRequestResponse.Value);
        }
Beispiel #15
0
        public async Task DeleteAccount_GivenUserWithSimpleRelations_UserAndRelationsDeleted()
        {
            GetDatabaseContext getContext = ContextUtilities.CreateInMemoryContext(_output);
            int johnDoeId;

            // Arrange
            using (IDatabaseContext context = getContext())
            {
                User john = ContextUtilities.CreateJohnDoe();

                context.PasswordResets.Add(new PasswordReset {
                    Requested = DateTime.UtcNow, User = john
                });
                context.Sessions.Add(new Session {
                    Created = DateTime.UtcNow, User = john
                });

                await context.SaveChangesAsync();

                johnDoeId = john.Id;
            }

            // Act
            (UserController controller, _, _, _) = CreateController(getContext, johnDoeId);
            IActionResult response = await controller.DeleteAccount();

            // Assert
            Assert.IsType <OkResult>(response);
            using (IDatabaseContext context = getContext())
            {
                Assert.Empty(context.Users);
                Assert.Empty(context.Sessions);
                Assert.Empty(context.PasswordResets);
            }
        }
Beispiel #16
0
        public async Task SetNewPassword_GivenCorrectCurrentPassword_ChangesPassword()
        {
            GetDatabaseContext getContext = ContextUtilities.CreateInMemoryContext(_output);
            User         john;
            const string CorrectCurrentPassword = "******";
            const string NewPassword            = "******";
            const string NewPasswordHash        = "Néw P@ssw0rd";

            // Arrange
            using (IDatabaseContext context = getContext())
            {
                john = context.Users.Add(ContextUtilities.CreateJohnDoe()).Entity;

                await context.SaveChangesAsync();
            }

            // Act
            (UserController controller, _, Mock <IPasswordService> passwordServiceMock, _) = CreateController(getContext, john.Id);
            passwordServiceMock.Setup(p => p.VerifyPassword(CorrectCurrentPassword, john.PasswordHash)).Returns(true);
            passwordServiceMock.Setup(p => p.HashPassword(NewPassword)).Returns(NewPasswordHash);

            IActionResult response = await controller.SetNewPassword(new SetPasswordDto { CurrentPassword = CorrectCurrentPassword, NewPassword = NewPassword });

            // Assert
            Assert.IsType <OkResult>(response);
            using (IDatabaseContext context = getContext())
            {
                User loadedUser = context.Users.Single();
                Assert.Equal(NewPasswordHash, loadedUser.PasswordHash);
            }
        }
        public async Task RemoveFromEvent_GivenParticipatingUser_UserLeavesEventAndAppointments()
        {
            GetDatabaseContext getContext = ContextUtilities.CreateInMemoryContext(_output);
            int johnDoeId;
            int eventId;
            int appointmentId;

            // Arrange
            using (IDatabaseContext context = getContext())
            {
                EntityEntry <User> john = context.Users.Add(ContextUtilities.CreateJohnDoe());

                Event @event = DummyEvent(ContextUtilities.CreateRichardRoe());

                context.EventParticipations.Add(new EventParticipation {
                    Participant = john.Entity, Event = @event
                });

                var appointment = new Appointment
                {
                    Event     = @event,
                    StartTime = DateTime.UtcNow + TimeSpan.FromDays(1)
                };

                context.AppointmentParticipations.Add(new AppointmentParticipation {
                    Appointment = appointment, Participant = john.Entity, AppointmentParticipationAnswer = AppointmentParticipationAnswer.Accepted
                });

                await context.SaveChangesAsync();

                johnDoeId     = john.Entity.Id;
                eventId       = @event.Id;
                appointmentId = appointment.Id;
            }

            // Act
            (ParticipateEventController participateEventController, Mock <AssertingNotificationService> notificationServiceMock) = CreateController(getContext, johnDoeId);
            Expression <Func <AssertingNotificationService, Task> > sendLastMinuteChangeExpression = n => n.SendLastMinuteChangeIfRequiredAsync(It.Is <Appointment>(a => a.Id == appointmentId));

            notificationServiceMock.Setup(sendLastMinuteChangeExpression).CallBase();

            IActionResult response = await participateEventController.RemoveFromEvent(new RemoveFromEventDto
            {
                EventId = eventId,
                UserId  = johnDoeId
            });

            // Assert
            Assert.IsType <OkResult>(response);
            notificationServiceMock.Verify(sendLastMinuteChangeExpression, Times.Once);
            using (IDatabaseContext context = getContext())
            {
                Assert.Single(context.Events);
                Assert.Empty(context.EventParticipations);
                Assert.Single(context.Appointments);
                Assert.Empty(context.AppointmentParticipations);
            }
        }
Beispiel #18
0
        public async Task DeleteAccount_GivenUserWithEvents_UserAndEventsDeleted()
        {
            GetDatabaseContext getContext = ContextUtilities.CreateInMemoryContext(_output);
            int johnDoeId;
            int eventId1;
            int eventId2;

            // Arrange
            using (IDatabaseContext context = getContext())
            {
                User john = ContextUtilities.CreateJohnDoe();

                Event event1 = DummyEvent(john);
                Event event2 = DummyEvent(john, true);
                context.EventParticipations.Add(new EventParticipation {
                    Event = event1, Participant = john
                });
                context.EventParticipations.Add(new EventParticipation {
                    Event = event2, Participant = john
                });

                context.EventInvitations.Add(new EventInvitation {
                    Event = event1, Requested = DateTime.UtcNow
                });
                context.EventInvitations.Add(new EventInvitation {
                    Event = event2, Requested = DateTime.UtcNow
                });

                await context.SaveChangesAsync();

                johnDoeId = john.Id;
                eventId1  = event1.Id;
                eventId2  = event2.Id;
            }

            // Act
            (UserController controller, _, _, Mock <AssertingNotificationService> notificationMock) = CreateController(getContext, johnDoeId);

            notificationMock.Setup(n => n.NotifyEventDeletedAsync(It.Is <EventNotificationInformation>(e => e.Id == eventId1))).CallBase();
            notificationMock.Setup(n => n.NotifyEventDeletedAsync(It.Is <EventNotificationInformation>(e => e.Id == eventId2))).CallBase();

            IActionResult response = await controller.DeleteAccount();

            // Assert
            notificationMock.Verify(n => n.NotifyEventDeletedAsync(It.Is <EventNotificationInformation>(e => e.Id == eventId1)), Times.Once);
            notificationMock.Verify(n => n.NotifyEventDeletedAsync(It.Is <EventNotificationInformation>(e => e.Id == eventId2)), Times.Once);

            Assert.IsType <OkResult>(response);
            using (IDatabaseContext context = getContext())
            {
                Assert.Empty(context.Users);
                Assert.Empty(context.Events);
                Assert.Empty(context.EventParticipations);
            }
        }
        public async Task RemoveFromEvent_GivenDeclinedUser_NoUpdateSent()
        {
            GetDatabaseContext getContext = ContextUtilities.CreateInMemoryContext(_output);
            int johnDoeId;
            int eventId;

            // Arrange
            using (IDatabaseContext context = getContext())
            {
                EntityEntry <User> john = context.Users.Add(ContextUtilities.CreateJohnDoe());

                Event @event = DummyEvent(ContextUtilities.CreateRichardRoe());

                context.EventParticipations.Add(new EventParticipation {
                    Participant = john.Entity, Event = @event
                });

                var appointment = new Appointment
                {
                    Event     = @event,
                    StartTime = DateTime.UtcNow + TimeSpan.FromDays(1)
                };

                context.AppointmentParticipations.Add(new AppointmentParticipation {
                    Appointment = appointment, Participant = john.Entity, AppointmentParticipationAnswer = AppointmentParticipationAnswer.Declined
                });
                context.AppointmentParticipations.Add(new AppointmentParticipation {
                    Appointment = appointment, Participant = john.Entity, AppointmentParticipationAnswer = null
                });

                await context.SaveChangesAsync();

                johnDoeId = john.Entity.Id;
                eventId   = @event.Id;
            }

            // Act
            (ParticipateEventController participateEventController, Mock <AssertingNotificationService> _) = CreateController(getContext, johnDoeId);

            IActionResult response = await participateEventController.RemoveFromEvent(new RemoveFromEventDto
            {
                EventId = eventId,
                UserId  = johnDoeId
            });

            // Assert
            Assert.IsType <OkResult>(response);
            using (IDatabaseContext context = getContext())
            {
                Assert.Single(context.Events);
                Assert.Empty(context.EventParticipations);
                Assert.Single(context.Appointments);
                Assert.Empty(context.AppointmentParticipations);
            }
        }
        public async Task RunAsync_GivenFutureAppointments_SendsReminder()
        {
            GetDatabaseContext getContext = ContextUtilities.CreateInMemoryContext(_output);

            // Arrange
            Appointment appointment = await CreateTestDataAsync(getContext, DateTime.UtcNow + TimeSpan.FromHours(ReminderTimeWindowInHours));

            // Act
            (CronSendReminderAndSummaryService service, Mock <AssertingNotificationService> notificationServiceMock) = CreateService(getContext);
            notificationServiceMock.Setup(n => n.SendAndUpdateRemindersAsync(It.Is <Appointment>(a => a.Id == appointment.Id))).CallBase();
            await service.RunAsync(CancellationToken.None);

            // Assert
            notificationServiceMock.Verify(n => n.SendAndUpdateRemindersAsync(It.Is <Appointment>(a => a.Id == appointment.Id)), Times.Once);
        }
        public async Task ResetPassword_GivenInvalidPasswordReset_RequestRejected()
        {
            GetDatabaseContext getContext = ContextUtilities.CreateInMemoryContext(_output);

            // Act
            (ResetPasswordController controller, _, _) = CreateController(getContext, null);

            IActionResult response = await controller.ResetPassword(new ResetPasswordDto { NewPassword = "******", PasswordResetToken = Guid.NewGuid() });

            // Assert
            Assert.IsType <BadRequestObjectResult>(response);
            var badRequestResponse = (BadRequestObjectResult)response;

            Assert.Equal(RequestStringMessages.ResetCodeInvalid, badRequestResponse.Value);
        }
        public async Task RunAsync_GivenUnreadMessages_NotificationsSent()
        {
            GetDatabaseContext getContext = ContextUtilities.CreateInMemoryContext(_output);

            DateTime latestSentDate = DateTime.UtcNow - TimeSpan.FromHours(1);

            // Arrange
            IEnumerable <ChatMessage> CreateMessagesFunc(User john, User richard)
            {
                yield return(new ChatMessage {
                    Author = john, Content = "Some early message", SentDate = latestSentDate - TimeSpan.FromSeconds(60)
                });

                yield return(new ChatMessage {
                    Author = john, Content = "Some late message", SentDate = latestSentDate
                });

                yield return(new ChatMessage {
                    Author = richard, Content = "Some average message", SentDate = latestSentDate - TimeSpan.FromSeconds(30)
                });
            }

            Event @event = await CreateTestDataAsync(getContext, latestSentDate - TimeSpan.FromHours(1), DateTime.MinValue, CreateMessagesFunc);

            // Act
            (CronSendMissedChatMessagesService service, Mock <AssertingNotificationService> notificationServiceMock) = CreateService(getContext);
            Expression <Func <AssertingNotificationService, Task> > mockExpression =
                n => n.NotifyUnreadChatMessagesAsync(It.Is <ChatMessagesNotificationInformation>(
                                                         a => (a.EventId == @event.Id) && (a.Messages.Count == 3)));

            notificationServiceMock.Setup(mockExpression).CallBase();
            await service.RunAsync(CancellationToken.None);

            // Assert
            notificationServiceMock.Verify(mockExpression, Times.Exactly(2));
            using (IDatabaseContext context = getContext())
            {
                List <EventParticipation> participations = await context.EventParticipations.ToListAsync();

                Assert.Equal(2, participations.Count);
                foreach (EventParticipation eventParticipation in participations)
                {
                    Assert.Equal(latestSentDate, eventParticipation.LastReadMessageSentDate);
                }
            }
        }
Beispiel #23
0
        public async Task GetOverview_GivenSomeEvents_OnlyShowsPublicEvents()
        {
            GetDatabaseContext getContext = ContextUtilities.CreateInMemoryContext(_output);
            int publicEventId1;
            int publicEventId2;
            int privateEventId;
            int johnId;

            // Arrange
            using (IDatabaseContext context = getContext())
            {
                EntityEntry <User> john = context.Users.Add(ContextUtilities.CreateJohnDoe());
                User  organizer         = ContextUtilities.CreateRichardRoe();
                Event publicEvent1      = DummyEvent(organizer);
                Event publicEvent2      = DummyEvent(organizer);
                Event privateEvent      = DummyEvent(organizer, true);
                context.Events.Add(publicEvent1);
                context.Events.Add(publicEvent2);
                context.Events.Add(privateEvent);

                await context.SaveChangesAsync();

                publicEventId1 = publicEvent1.Id;
                publicEventId2 = publicEvent2.Id;
                privateEventId = privateEvent.Id;
                johnId         = john.Entity.Id;
            }

            // Act
            (ParticipateEventController participateEventController, _) = CreateController(getContext, johnId);

            IActionResult response = await participateEventController.GetOverview();

            // Assert
            Assert.IsType <OkObjectResult>(response);
            var okObjectResult = (OkObjectResult)response;
            var eventOverview  = okObjectResult.Value as EventOverview;

            Assert.NotNull(eventOverview);
            Assert.Empty(eventOverview.YourEvents);
            Assert.Equal(2, eventOverview.PublicEvents.Count);
            Assert.Contains(publicEventId1, eventOverview.PublicEvents.Select(e => e.EventId));
            Assert.Contains(publicEventId2, eventOverview.PublicEvents.Select(e => e.EventId));
            Assert.DoesNotContain(privateEventId, eventOverview.PublicEvents.Select(e => e.EventId));
        }
Beispiel #24
0
        public async Task RequestPasswordReset_GivenNonExistingUser_RequestRejected()
        {
            GetDatabaseContext getContext = ContextUtilities.CreateInMemoryContext(_output);

            // Act
            (ResetPasswordController controller, _, _) = CreateController(getContext, null);

            IActionResult response = await controller.RequestPasswordReset(new RequestPasswordResetDto { Email = "*****@*****.**" });

            // Assert
            Assert.IsType <BadRequestObjectResult>(response);
            var badRequestResponse = (BadRequestObjectResult)response;

            Assert.Equal(RequestStringMessages.NoProfileWithEmailFound, badRequestResponse.Value);
            using (IDatabaseContext context = getContext())
            {
                Assert.Empty(context.PasswordResets);
            }
        }
        public async Task DeleteEvent_GivenEventUserOnlyParticipates_EventNotDeleted(bool isPrivate)
        {
            GetDatabaseContext getContext = ContextUtilities.CreateInMemoryContext(_output);
            int johnDoeId;
            int eventId;

            // Arrange
            using (IDatabaseContext context = getContext())
            {
                User john    = ContextUtilities.CreateJohnDoe();
                User richard = ContextUtilities.CreateRichardRoe();

                Event @event = DummyEvent(richard, isPrivate);

                context.EventParticipations.Add(new EventParticipation {
                    Event = @event, Participant = john
                });
                context.EventParticipations.Add(new EventParticipation {
                    Event = @event, Participant = richard
                });

                await context.SaveChangesAsync();

                johnDoeId = john.Id;
                eventId   = @event.Id;
            }

            // Act
            (OrganizeEventController controller, _) = CreateController(getContext, johnDoeId);

            IActionResult response = await controller.DeleteEvent(eventId);

            // Assert
            Assert.IsType <BadRequestObjectResult>(response);
            var objectResult = (BadRequestObjectResult)response;

            Assert.Equal(RequestStringMessages.OrganizerRequired, objectResult.Value);
            using (IDatabaseContext context = getContext())
            {
                Assert.Single(context.Events);
            }
        }
        public async Task Register_GivenCorrectData_UserRegistered()
        {
            GetDatabaseContext getContext = ContextUtilities.CreateInMemoryContext(_output);

            // Arrange
            var data = new RegisterDto {
                Email = "*****@*****.**", FullName = "New User", Password = "******"
            };
            var          newSessionGuid = Guid.NewGuid();
            const string PasswordHash   = "P@ssw0rd";

            // Act
            (UserController controller, Mock <ISessionService> sessionServiceMock, Mock <IPasswordService> passwordServiceMock, _) = CreateController(getContext, null);
            sessionServiceMock.Setup(s => s.CreateSessionAsync(It.IsAny <int>(), true)).ReturnsAsync(newSessionGuid);
            passwordServiceMock.Setup(s => s.HashPassword(data.Password)).Returns(PasswordHash);
            IActionResult response = await controller.Register(data);

            // Assert
            sessionServiceMock.Verify(s => s.CreateSessionAsync(It.IsAny <int>(), true), Times.Once);
            passwordServiceMock.Verify(s => s.HashPassword(data.Password), Times.Once);

            Assert.IsType <OkObjectResult>(response);
            var objectResult = (OkObjectResult)response;
            var session      = objectResult.Value as FrontendSession;

            using (IDatabaseContext context = getContext())
            {
                Assert.Single(context.Users);
                User loadedUser = context.Users.First();
                Assert.Equal(data.FullName, loadedUser.FullName);
                Assert.Equal(data.Email, loadedUser.Email);
                Assert.Equal(PasswordHash, loadedUser.PasswordHash);

                Assert.NotNull(session);
                Assert.Equal(loadedUser.Id, session.UserId);
                Assert.Equal(loadedUser.Email, session.Email);
                Assert.Equal(loadedUser.FullName, session.FullName);
                Assert.Equal(newSessionGuid, session.Token);
            }
        }
        public async Task ResetPassword_GivenValidPasswordReset_NewPasswordIsSet()
        {
            GetDatabaseContext getContext = ContextUtilities.CreateInMemoryContext(_output);
            Guid         resetToken;
            const string NewPassword     = "******";
            const string NewPasswordHash = "P@ssw0rd";

            // Arrange
            using (IDatabaseContext context = getContext())
            {
                User john  = ContextUtilities.CreateJohnDoe();
                var  reset = new PasswordReset {
                    Requested = DateTime.UtcNow, User = john
                };
                context.PasswordResets.Add(reset);

                await context.SaveChangesAsync();

                resetToken = reset.Token;
            }

            // Act
            (ResetPasswordController controller, Mock <IPasswordService> passwordServiceMock, _) = CreateController(getContext, null);
            passwordServiceMock.Setup(p => p.HashPassword(NewPassword)).Returns(NewPasswordHash);

            IActionResult response = await controller.ResetPassword(new ResetPasswordDto { NewPassword = NewPassword, PasswordResetToken = resetToken });

            // Assert
            Assert.IsType <OkResult>(response);
            using (IDatabaseContext context = getContext())
            {
                passwordServiceMock.Verify(p => p.HashPassword(NewPassword), Times.Once);
                PasswordReset passwordReset = await context.PasswordResets.Include(p => p.User).SingleOrDefaultAsync();

                Assert.NotNull(passwordReset);
                Assert.True(passwordReset.Used);
                Assert.Equal(NewPasswordHash, passwordReset.User.PasswordHash);
            }
        }
Beispiel #28
0
        public async Task Authenticate_GivenPasswordWhichNeedsRehash_RehashesPassword()
        {
            GetDatabaseContext getContext      = ContextUtilities.CreateInMemoryContext(_output);
            const string       NewPasswordHash = "NewPasswordHash";

            // Arrange
            using (IDatabaseContext context = getContext())
            {
                EntityEntry <User> userEntry = context.Users.Add(ContextUtilities.CreateJohnDoe());

                userEntry.Entity.Email        = Email;
                userEntry.Entity.PasswordHash = PasswordHash;

                await context.SaveChangesAsync();
            }

            // Act
            var passwordServiceMock = new Mock <IPasswordService>();

            passwordServiceMock.Setup(p => p.NeedsRehash(PasswordHash)).Returns(true);
            passwordServiceMock.Setup(p => p.VerifyPassword(Password, PasswordHash)).Returns(true);
            passwordServiceMock.Setup(p => p.HashPassword(Password)).Returns(NewPasswordHash);

            var authenticationService = new AuthenticationService(passwordServiceMock.Object, getContext, DummyLogger <AuthenticationService>());

            (bool isAuthenticated, _) = await authenticationService.AuthenticateAsync(Email, Password);

            // Assert
            passwordServiceMock.Verify(p => p.NeedsRehash(PasswordHash), Times.Once);
            passwordServiceMock.Verify(p => p.HashPassword(Password), Times.Once);

            Assert.True(isAuthenticated);
            using (IDatabaseContext context = getContext())
            {
                User user = context.Users.Single();
                Assert.Equal(NewPasswordHash, user.PasswordHash);
            }
        }
        public async Task JoinEvent_GivenNotParticipatingUser_UserCanJoin()
        {
            GetDatabaseContext getContext = ContextUtilities.CreateInMemoryContext(_output);
            int johnDoeId;
            int eventId;

            // Arrange
            using (IDatabaseContext context = getContext())
            {
                EntityEntry <User> john = context.Users.Add(ContextUtilities.CreateJohnDoe());

                Event @event = DummyEvent(ContextUtilities.CreateRichardRoe());
                context.Events.Add(@event);

                await context.SaveChangesAsync();

                johnDoeId = john.Entity.Id;
                eventId   = @event.Id;
            }

            // Act
            (ParticipateEventController participateEventController, _) = CreateController(getContext, johnDoeId);

            IActionResult response = await participateEventController.JoinEvent(new JoinEventDto
            {
                EventId = eventId
            });

            // Assert
            Assert.IsType <OkResult>(response);
            using (IDatabaseContext context = getContext())
            {
                Event loadedEvent = await context.Events.Include(e => e.EventParticipations).FirstOrDefaultAsync(e => e.Id == eventId);

                Assert.NotNull(loadedEvent);
                Assert.Contains(johnDoeId, loadedEvent.EventParticipations.Select(e => e.ParticipantId));
            }
        }
        public async Task ConfigureNotifications_GivenParticipatingEvent_NotificationsConfigured()
        {
            GetDatabaseContext getContext = ContextUtilities.CreateInMemoryContext(_output);
            int eventId;
            int johnId;

            // Arrange
            using (IDatabaseContext context = getContext())
            {
                EntityEntry <User> john = context.Users.Add(ContextUtilities.CreateJohnDoe());
                User  organizer         = ContextUtilities.CreateRichardRoe();
                Event @event            = DummyEvent(organizer);
                context.Events.Add(@event);
                context.EventParticipations.Add(new EventParticipation {
                    Event = @event, Participant = john.Entity, SendLastMinuteChangesEmail = false, SendReminderEmail = false, SendSummaryEmail = false
                });

                await context.SaveChangesAsync();

                eventId = @event.Id;
                johnId  = john.Entity.Id;
            }

            // Act
            (ParticipateEventController participateEventController, _) = CreateController(getContext, johnId);

            IActionResult response = await participateEventController.ConfigureNotifications(new NotificationConfigurationDto { EventId = eventId, SendReminderEmail = true, SendSummaryEmail = true, SendLastMinuteChangesEmail = true });

            // Assert
            Assert.IsType <OkResult>(response);
            using (IDatabaseContext context = getContext())
            {
                EventParticipation eventParticipation = context.EventParticipations.Single();
                Assert.True(eventParticipation.SendSummaryEmail);
                Assert.True(eventParticipation.SendLastMinuteChangesEmail);
                Assert.True(eventParticipation.SendReminderEmail);
            }
        }