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);
        }
Exemple #2
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);
        }
        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);
        }
Exemple #4
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);
        }
Exemple #5
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);
            }
        }
Exemple #6
0
        public async Task CreateSession_GivenIsActiveFalse_SessionIsNotActivated()
        {
            (GetDatabaseContext getContext, SessionService sessionService) = SetupSessionService();
            int johnDoeId;

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

                johnDoeId = userEntry.Entity.Id;
            }

            // Act
            Guid sessionId = await sessionService.CreateSessionAsync(johnDoeId, false);

            // Assert
            using (IDatabaseContext context = getContext())
            {
                Session createdSession = await context.Sessions.FindAsync(sessionId);

                Assert.NotNull(createdSession);
                Assert.InRange(createdSession.Created, DateTime.UtcNow - TimeSpan.FromMinutes(1), DateTime.UtcNow);
                Assert.Null(createdSession.ValidUntil);
            }
        }
Exemple #7
0
        public async Task InvalidateSession_GivenInvalidSession_SessionUnchanged()
        {
            (GetDatabaseContext getContext, SessionService sessionService) = SetupSessionService();
            Session invalidUserSession;

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

                invalidUserSession = new Session
                {
                    Created    = DateTime.UtcNow - TimeSpan.FromHours(10),
                    ValidUntil = DateTime.UtcNow - TimeSpan.FromHours(5),
                    User       = userEntry.Entity
                };
                context.Sessions.Add(invalidUserSession);
                await context.SaveChangesAsync();
            }

            // Act
            await sessionService.InvalidateSessionAsync(invalidUserSession.Token);

            // Assert
            using (IDatabaseContext context = getContext())
            {
                Session newlyLoadedSession = await context.Sessions.FindAsync(invalidUserSession.Token);

                Assert.NotNull(newlyLoadedSession);
                Assert.Equal(invalidUserSession.ValidUntil, newlyLoadedSession.ValidUntil);
            }
        }
Exemple #8
0
        public async Task GetSession_GivenExpiredUnusedSession_SessionUnchanged()
        {
            _configuration.TimeSpans.UpdateValidUntilTimeSpan = TimeSpan.Zero;
            (GetDatabaseContext getContext, SessionService sessionService) = SetupSessionService();
            Session invalidUserSession;

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

                invalidUserSession = new Session
                {
                    Created    = DateTime.UtcNow - _configuration.TimeSpans.UnusedSessionExpirationTimeout,
                    ValidUntil = null,
                    User       = userEntry.Entity
                };
                context.Sessions.Add(invalidUserSession);
                await context.SaveChangesAsync();
            }

            // Act
            Session loadedSession = await sessionService.GetAndExtendSessionAsync(invalidUserSession.Token);

            // Assert
            using (IDatabaseContext context = getContext())
            {
                Assert.Null(loadedSession);

                Session newlyLoadedSession = await context.Sessions.FindAsync(invalidUserSession.Token);

                Assert.NotNull(newlyLoadedSession);
                Assert.Null(newlyLoadedSession.ValidUntil);
            }
        }
        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);
        }
        private static async Task <Event> CreateTestDataAsync(GetDatabaseContext getContext, DateTime lastReadJohn, DateTime lastReadRichard, Func <User, User, IEnumerable <ChatMessage> > createMessagesFunc)
        {
            using (IDatabaseContext context = getContext())
            {
                User john    = ContextUtilities.CreateJohnDoe();
                User richard = ContextUtilities.CreateRichardRoe();

                var @event = new Event
                {
                    Title        = "Chatty event",
                    Description  = "An event with an active chat",
                    MeetingPlace = "Somewhere",
                    Organizer    = john,
                    ReminderTimeWindowInHours = 42,
                    SummaryTimeWindowInHours  = 24,
                    EventParticipations       = new List <EventParticipation>
                    {
                        new EventParticipation {
                            Participant = john, LastReadMessageSentDate = lastReadJohn
                        },
                        new EventParticipation {
                            Participant = richard, LastReadMessageSentDate = lastReadRichard
                        }
                    },
                    ChatMessages = createMessagesFunc(john, richard).ToList()
                };

                context.Events.Add(@event);

                await context.SaveChangesAsync();

                return(@event);
            }
        }
Exemple #11
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);
            }
        }
Exemple #12
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 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);
        }
        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);
        }
Exemple #15
0
        public async Task GetSession_GivenValidSessionWhichWasRecentlyUpdated_SessionUnchanged()
        {
            _configuration.TimeSpans.UpdateValidUntilTimeSpan = TimeSpan.FromHours(1);
            (GetDatabaseContext getContext, SessionService sessionService) = SetupSessionService();
            Guid     sessionToken;
            DateTime originalSessionValidUntil = DateTime.UtcNow + _configuration.TimeSpans.InactiveSessionTimeout;

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

                var validUserSession = new Session
                {
                    Created    = DateTime.UtcNow,
                    ValidUntil = originalSessionValidUntil,
                    User       = userEntry.Entity
                };
                context.Sessions.Add(validUserSession);
                await context.SaveChangesAsync();

                sessionToken = validUserSession.Token;
            }

            // Act
            await Task.Delay(1);

            Session loadedSession = await sessionService.GetAndExtendSessionAsync(sessionToken);

            // Assert
            Assert.NotNull(loadedSession);
            Assert.Equal(originalSessionValidUntil, loadedSession.ValidUntil);
        }
        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);
        }
Exemple #17
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 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);
        }
Exemple #19
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);
            }
        }
        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);
            }
        }
        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);
            }
        }
Exemple #22
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);
            }
        }
        private static async Task <Appointment> CreateTestDataAsync(GetDatabaseContext getContext, DateTime startTime)
        {
            using (IDatabaseContext context = getContext())
            {
                User john    = ContextUtilities.CreateJohnDoe();
                User richard = ContextUtilities.CreateRichardRoe();

                var @event = new Event
                {
                    Title        = "Upcoming event",
                    Description  = "An event with upcoming appointments",
                    MeetingPlace = "Somewhere",
                    Organizer    = john,
                    ReminderTimeWindowInHours = ReminderTimeWindowInHours,
                    SummaryTimeWindowInHours  = SummaryTimeWindowInHours,
                    EventParticipations       = new List <EventParticipation>
                    {
                        new EventParticipation {
                            Participant = john
                        },
                        new EventParticipation {
                            Participant = richard
                        }
                    }
                };

                var appointment = new Appointment
                {
                    Event = @event,
                    AppointmentParticipations = new List <AppointmentParticipation>
                    {
                        new AppointmentParticipation {
                            Participant = john
                        },
                        new AppointmentParticipation {
                            Participant = richard
                        }
                    },
                    StartTime = startTime
                };

                context.Appointments.Add(appointment);

                await context.SaveChangesAsync();

                return(appointment);
            }
        }
Exemple #24
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));
        }
        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);
            }
        }
Exemple #26
0
        public async Task GetSession_GivenValidSession_ExtendsSession()
        {
            _configuration.TimeSpans.UpdateValidUntilTimeSpan = TimeSpan.Zero;
            (GetDatabaseContext getContext, SessionService sessionService) = SetupSessionService();
            Guid sessionToken;

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

                var validUserSession = new Session
                {
                    Created    = DateTime.UtcNow,
                    ValidUntil = null,
                    User       = userEntry.Entity
                };
                context.Sessions.Add(validUserSession);
                await context.SaveChangesAsync();

                sessionToken = validUserSession.Token;
            }

            // Act
            Session loadedSession = await sessionService.GetAndExtendSessionAsync(sessionToken);

            // Assert
            Assert.NotNull(loadedSession);
            Assert.True(loadedSession.ValidUntil >= DateTime.UtcNow);

            DateTime firstValidUntil = loadedSession.ValidUntil.Value;

            await Task.Delay(1);

            loadedSession = await sessionService.GetAndExtendSessionAsync(loadedSession.Token);

            Assert.NotNull(loadedSession);
            Assert.True(firstValidUntil < loadedSession.ValidUntil);
        }
        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);
            }
        }
Exemple #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);
            }
        }