Beispiel #1
0
        public async Task Create_User_Email_Already_Exists()
        {
            var connection = TestHelper.GetConnection();
            var options    = TestHelper.GetMockDBOptions(connection);

            try
            {
                // Run the test against one instance of the context
                using (var context = new AppcentTodoContext(options))
                {
                    TestHelper.EnsureCreated(context);
                    var service = new RegisterUserCommandHandler(context, TestHelper.GetMapperInstance());
                    var command = new RegisterUserCommand();
                    command.Data = new RegisterUserRequest
                    {
                        Email     = "*****@*****.**",
                        FirstName = "test firstname",
                        LastName  = "test lastname",
                        Password  = "******",
                        UserName  = "******"
                    };
                    var result = await service.Execute(command);

                    Assert.False(result.Result.IsSuccess);
                    Assert.Equal("Email is already in use", result.Result.Error.ErrorText);
                }
            }
            finally
            {
                connection.Close();
            }
        }
Beispiel #2
0
        public void Arrange()
        {
            _registerUserCommandValidator = new Mock <IValidator <RegisterUserCommand> >();
            _auditService = new Mock <IAuditService>();

            _passwordService = new Mock <IPasswordService>();
            _passwordService.Setup(s => s.GenerateAsync(It.IsAny <string>()))
            .Returns(Task.FromResult(new SecuredPassword
            {
                HashedPassword = "******",
                Salt           = "Generated_Salt",
                ProfileId      = "Password_Profile_Id"
            }));

            _userRepository = new Mock <IUserRepository>();

            _communicationService = new Mock <ICommunicationService>();

            _codeGenerator = new Mock <ICodeGenerator>();
            _codeGenerator.Setup(x => x.GenerateAlphaNumeric(6))
            .Returns("ABC123XYZ");

            _auditService = new Mock <IAuditService>();

            _logger = new Mock <ILogger>();

            _registerUserCommandHandler = new RegisterUserCommandHandler(_registerUserCommandValidator.Object,
                                                                         _passwordService.Object,
                                                                         _userRepository.Object,
                                                                         _communicationService.Object,
                                                                         _codeGenerator.Object,
                                                                         _logger.Object,
                                                                         _auditService.Object);
        }
        public async Task Should_Register_A_New_User()
        {
            Guid userId = Guid.NewGuid();
            IApplicationDbContext dbContext = Testing.GetService <IApplicationDbContext>();

            Mock <IGuidGenerator> guidGeneratorStub = new Mock <IGuidGenerator>();

            guidGeneratorStub.Setup(m => m.GetNextAsync()).ReturnsAsync(userId);

            var sut = new RegisterUserCommandHandler(guidGeneratorStub.Object, dbContext);

            RegisterUserCommand request = new RegisterUserCommand()
            {
                Username = "******",
                Password = "******",
                About    = "I like TDD"
            };

            var registeredUserVm = await sut.Handle(request, CancellationToken.None);

            // output verification
            registeredUserVm.Id.Should().Be(userId);
            registeredUserVm.Username.Should().Be(request.Username);
            registeredUserVm.About.Should().Be(request.About);

            // state verification
            var registeredUser = await dbContext.Users.SingleAsync(u => u.Id == userId);

            registeredUser.Username.Should().Be(request.Username);
            registeredUser.Password.Should().Be(request.Password);
            registeredUser.About.Should().Be(request.About);
        }
Beispiel #4
0
        /// <summary>
        ///     Start the command bus example.
        /// </summary>
        public static void Main()
        {
            Console.WriteLine("==== [StructureMap] ====");

            try
            {
                Task.Factory.StartNew(StructureMapExample.Go).Wait();
            }
            catch (Exception ex1)
            {
                Console.WriteLine("Exception - " + ex1.Message);
            }

            RegisterUserCommandHandler.ResetUsers();

            Console.WriteLine("==== [Autofac] ====");

            try
            {
                Task.Factory.StartNew(AutofacExample.Go).Wait();
            }
            catch (Exception ex1)
            {
                Console.WriteLine("Exception - " + ex1.Message);
            }

            Console.WriteLine("Press Enter to exit...");
            Console.ReadLine();
        }
Beispiel #5
0
        public async Task Create_User()
        {
            var connection = TestHelper.GetConnection();
            var options    = TestHelper.GetMockDBOptions(connection);

            try
            {
                using (var context = new AppcentTodoContext(options))
                {
                    var service = new RegisterUserCommandHandler(context, TestHelper.GetMapperInstance());
                    var command = new RegisterUserCommand();
                    command.Data = new RegisterUserRequest
                    {
                        Email     = "test email",
                        FirstName = "test firstname",
                        LastName  = "test lastname",
                        Password  = "******",
                        UserName  = "******"
                    };
                    var result = await service.Execute(command);

                    Assert.True(result.Result.IsSuccess);
                }

                using (var context = new AppcentTodoContext(options))
                {
                    var count = context.AcUsers.Where(e => e.FirstName == "test firstname");
                    Assert.Equal(1, count.Count());
                }
            }
            finally
            {
                connection.Close();
            }
        }
Beispiel #6
0
        public async Task Should_Register_User()
        {
            Result <int> userRegistrationResult;

            var userRegistrationCommand = new RegisterUserCommand(
                "registereduser",
                "registered",
                "user",
                "password",
                "*****@*****.**",
                "registered user bio",
                Convert.FromBase64String(_testFixture.GetTestPictureBase64()));

            using (var session = _testFixture.OpenSession(_output))
            {
                var sut = new RegisterUserCommandHandler(session, Log.Logger);
                userRegistrationResult = await sut.Handle(userRegistrationCommand, default);
            }

            using (new AssertionScope())
            {
                userRegistrationResult.IsSuccess.Should().BeTrue();
                userRegistrationResult.Value.Should().BeGreaterThan(0);
                using (var session = _testFixture.OpenSession(_output))
                {
                    (await session.GetAsync <User>(userRegistrationResult.Value)).Should().NotBeNull();
                }
            }
        }
Beispiel #7
0
        public async Task RegisterUserCommand_UserRegisters_NewUserCreated()
        {
            var command = new RegisterUserCommand()
            {
                Username        = "******",
                Password        = "******",
                ConfirmPassword = "******",
                Name            = "Testname",
                Surname         = "Testsurname",
                BirthDate       = DateTime.Now,
                Email           = "*****@*****.**",
                Gender          = Gender.Male
            };

            UpdateUserCommand user;

            using (var dbContext = new JoggingTrackerDbContext(this._options))
            {
                dbContext.Roles.Add(new Role()
                {
                    Id = Guid.NewGuid(), Name = Role.UserRole
                });
                await dbContext.SaveChangesAsync();

                var commandHandler = new RegisterUserCommandHandler(this._securityProvider, this._serverTime, this._mapper, dbContext);
                user = await commandHandler.Handle(command);
            }

            using (var dbContext = new JoggingTrackerDbContext(this._options))
            {
                Assert.NotNull(await dbContext.Users.SingleAsync(u => u.Id == user.Id));
            }
        }
        public async Task UpdateUserRefreshTokenCommandHandler_GivenValidCommand_ShouldInsertedInDb()
        {
            var serviceProvider = _services
                                  .BuildServiceProvider();

            using (var scope = serviceProvider.CreateScope())
            {
                var scopedServices = scope.ServiceProvider;

                try
                {
                    // seed sample user data
                    var userManager = scopedServices.GetRequiredService <UserManager <User> >();
                    _logging = scopedServices.GetRequiredService <ILoggerFactory>();
                    var roleManager = scopedServices.GetRequiredService <RoleManager <Role> >();
                    await SecurityDbContextSeed.SeedRolesAsync(roleManager);

                    _commandHandler = new RegisterUserCommandHandler(userManager, _logging.CreateLogger <RegisterUserCommandHandler>());

                    _dbContext = scopedServices.GetRequiredService <SecurityDbContext>();
                    IUnitOfWork unitOfWork = new UnitOfWork(_dbContext);
                    _userRepository = new UserRepository(unitOfWork);
                    await _commandHandler.Handle(new RegisterUserCommand("test", "test2", "*****@*****.**", "15 sh", "dokki", "giza", "egypt", DateTime.Now, "", "P@ssw0rd"), CancellationToken.None);

                    var createdUser = await _userRepository.FindAsync(new UserSpecification("*****@*****.**"));

                    createdUser.ShouldNotBeNull();
                }
                catch (Exception ex)
                {
                    string.IsNullOrEmpty(ex.Message).ShouldBeTrue();
                }
            }
        }
Beispiel #9
0
 public void Setup()
 {
     _userRepository              = new Mock <IUserRepository>();
     _tokenHelper                 = new Mock <ITokenHelper>();
     loginUserQueryHandler        = new LoginUserQueryHandler(_userRepository.Object, _tokenHelper.Object);
     registerUserCommandHandler   = new RegisterUserCommandHandler(_userRepository.Object);
     forgotPasswordCommandHandler = new ForgotPasswordCommandHandler(_userRepository.Object);
 }
        public void TestInitialize()
        {
            this.reservedUsernames = new Mock <IReservedUsernameService>();

            // Give potentially side-effecting components strict mock behaviour.
            this.registerUser = new Mock <IRegisterUserDbStatement>(MockBehavior.Strict);
            this.userManager  = new Mock <IUserManager>(MockBehavior.Strict);

            this.target = new RegisterUserCommandHandler(this.registerUser.Object, this.reservedUsernames.Object, this.userManager.Object);
        }
Beispiel #11
0
    public async Task GivenAlreadyExistingUser_WhenCallingHandle_ThenResultShouldBeFailure()
    {
        var registerUserCommand = new RegisterUserCommand();

        var sut = new RegisterUserCommandHandler(_mockUserService, Context, Mapper);

        var result = await sut.Handle(registerUserCommand, CancellationToken.None);

        result.IsFailure.Should().BeTrue();
    }
Beispiel #12
0
    public async Task GivenAlreadyExistingUser_WhenCallingHandle_ThenUserAlreadyRegisteredErrorShouldBeReturned()
    {
        var registerUserCommand = new RegisterUserCommand();

        var sut = new RegisterUserCommandHandler(_mockUserService, Context, Mapper);

        var result = await sut.Handle(registerUserCommand, CancellationToken.None);

        result.Error.Should().Be(Errors.General.UserAlreadyRegistered());
    }
Beispiel #13
0
        public async Task GivenRegisterUserCommandHandler_WhenUserEmailAlreadyExists_ThenThrowsRestException()
        {
            _mockUserManager.FindByEmailAsync(_command.Email).Returns(_user);

            var registerCommandHandler =
                new RegisterUserCommandHandler(_mockUserManager, _mockJwtGenerator, _mockEventBus,
                                               _mockUserConfirmationEmail, _mockFailedIdentityResult);

            await Assert.ThrowsAsync <RestException>(() =>
                                                     registerCommandHandler.Handle(_command, CancellationToken.None));
        }
        public void RegisterUserCommandHandler_Sends_Email()
        {
            var handler = new RegisterUserCommandHandler(_repository, _mailClient, new ActivationMailTemplate(_appSettings));
            var command = new RegisterUserCommand("*****@*****.**", "test");

            handler.Execute(command);

            _mailClient.SentMessages.Should().HaveCount(1);
            _mailClient.SentMessages[0].Subject.Should().Be("Please activate your account");
            _mailClient.SentMessages[0].To.Should().Be("*****@*****.**");
        }
Beispiel #15
0
        public void Setup()
        {
            _userRepository = new Mock <IUserRepository>();
            _tokenHelper    = new Mock <ITokenHelper>();
            _mediator       = new Mock <IMediator>();
            _cacheManager   = new Mock <ICacheManager>();

            _loginUserQueryHandler        = new LoginUserQueryHandler(_userRepository.Object, _tokenHelper.Object, _mediator.Object, _cacheManager.Object);
            _registerUserCommandHandler   = new RegisterUserCommandHandler(_userRepository.Object);
            _forgotPasswordCommandHandler = new ForgotPasswordCommandHandler(_userRepository.Object);
        }
Beispiel #16
0
 public RegisterUserTest()
 {
     // Arrange
     Mediator = new Mock <IMediator>();
     Mapper   = new Mapper(new MapperConfiguration(cfg =>
     {
         cfg.AddProfile(new MappingProfile());
         cfg.ValidateInlineMaps = false;
     }));
     Logger  = new Mock <ILogger <RegisterUserCommandHandler> >();
     Handler = new RegisterUserCommandHandler(Mediator.Object, Mapper, Logger.Object);
 }
Beispiel #17
0
        GivenRegisterUserCommandHandler_WhenNewUserHasRegistered_ThenUserConfirmationEmailShouldBeCalled()
        {
            _mockUserManager.FindByEmailAsync(_command.Email).ReturnsNullForAnyArgs();
            _mockUserManager.CreateAsync(_user, _command.Password)
            .ReturnsForAnyArgs(Task.FromResult(IdentityResult.Success));

            var registerCommandHandler =
                new RegisterUserCommandHandler(_mockUserManager, _mockJwtGenerator, _mockEventBus,
                                               _mockUserConfirmationEmail, _mockFailedIdentityResult);

            await registerCommandHandler.Handle(_command, CancellationToken.None);

            await _mockUserConfirmationEmail.Received().Send(Arg.Any <AppUser>());
        }
Beispiel #18
0
    public async Task GivenValidRegisterUserCommand_WhenCallingHandle_ThenResultShouldBeSuccessful()
    {
        var registerUserCommand = new RegisterUserCommand();

        var mockUserService = Substitute.For <IUserService>();

        mockUserService.GetUserInfo(Arg.Any <CancellationToken>()).Returns(new TestUser(_fixture.Create <string>(), _fixture.Create <string>(), _fixture.Create <string>()));

        var sut = new RegisterUserCommandHandler(mockUserService, Context, Mapper);

        var result = await sut.Handle(registerUserCommand, CancellationToken.None);

        result.IsSuccess.Should().BeTrue();
    }
Beispiel #19
0
        public async Task GivenRegisterUserCommandHandler_WhenNewUserDetailsAreProvided_ThenCreatesNewUser()
        {
            _mockUserManager.FindByEmailAsync(_command.Email).ReturnsNullForAnyArgs();
            _mockUserManager.CreateAsync(_user, _command.Password)
            .ReturnsForAnyArgs(Task.FromResult(IdentityResult.Success));

            var registerCommandHandler =
                new RegisterUserCommandHandler(_mockUserManager, _mockJwtGenerator, _mockEventBus,
                                               _mockUserConfirmationEmail, _mockFailedIdentityResult);

            var registeredUser = await registerCommandHandler.Handle(_command, CancellationToken.None);

            Assert.NotNull(registeredUser);
        }
Beispiel #20
0
        GivenRegisterUserCommandHandler_WhenNewUserDetailsAreProvided_ThenShouldCallUserManagerToFindExistingUser()
        {
            _mockUserManager.FindByEmailAsync(_command.Email).ReturnsNullForAnyArgs();
            _mockUserManager.CreateAsync(_user, _command.Password)
            .ReturnsForAnyArgs(Task.FromResult(IdentityResult.Success));

            var registerCommandHandler =
                new RegisterUserCommandHandler(_mockUserManager, _mockJwtGenerator, _mockEventBus,
                                               _mockUserConfirmationEmail, _mockFailedIdentityResult);

            await registerCommandHandler.Handle(_command, CancellationToken.None);

            await _mockUserManager.Received().FindByEmailAsync(Arg.Any <string>());
        }
        public void RegisterUserCommandHandler_Fails_For_Existing_Email()
        {
            var handler = new RegisterUserCommandHandler(_repository, _mailClient, new ActivationMailTemplate(_appSettings));
            var command = new RegisterUserCommand("*****@*****.**", "test");

            _context.Users.Add(new User("*****@*****.**", "test"));

            var result = handler.Execute(command);

            result.Errors.Should().HaveCount(1);
            result.Errors[0].Expression.ToString().Should().Be("p => p.Email");
            result.Errors[0].Message.Should().Be("Email address already exists");
            _mailClient.SentMessages.Should().BeEmpty();
        }
        public void RegisterUserCommandHandler_Succeeds()
        {
            var handler = new RegisterUserCommandHandler(_repository, _mailClient, new ActivationMailTemplate(_appSettings));
            var command = new RegisterUserCommand("*****@*****.**", "test");

            var result = handler.Execute(command);
            var user   = _context.Users.SingleOrDefault();

            result.Errors.Should().BeEmpty();
            user.Should().NotBeNull();
            user.Status.Should().Be(UserStatus.New);
            user.UserEvents.Should().HaveCount(1);
            user.UserEvents.Single().Type.Should().Be(UserEventType.Registered);
        }
        public async Task GivenAlreadyExistingUser_Handle_ShouldReturnUserAlreadyRegisteredError()
        {
            var registerUserCommand = new RegisterUserCommand();

            var mockUserService = new Mock <IUserService>();

            mockUserService.Setup(service => service.GetUserInfo(It.IsAny <CancellationToken>()))
            .ReturnsAsync(new TestUser("test-id", "Test User", "*****@*****.**"));

            var sut = new RegisterUserCommandHandler(mockUserService.Object, Context, Mapper);

            var result = await sut.Handle(registerUserCommand, CancellationToken.None);

            result.Error.Code.ShouldBe(Errors.General.UserAlreadyRegistered().Code);
        }
        public async Task GivenNewUser_Handle_ShouldBeAbleToRegisterUser()
        {
            var registerUserCommand = new RegisterUserCommand();

            var mockUserService = new Mock <IUserService>();

            mockUserService.Setup(service => service.GetUserInfo(It.IsAny <CancellationToken>()))
            .ReturnsAsync(new TestUser("new-id", "New User", "*****@*****.**"));

            var sut = new RegisterUserCommandHandler(mockUserService.Object, Context, Mapper);

            var result = await sut.Handle(registerUserCommand, CancellationToken.None);

            result.IsSuccess.ShouldBe(true);
        }
Beispiel #25
0
        GivenRegisterUserCommandHandler_WhenNewUserFailedToRegister_ThenShouldCallFailedIdentityResult()
        {
            _mockUserManager.FindByEmailAsync(_command.Email).ReturnsNullForAnyArgs();
            _mockUserManager.CreateAsync(_user, _command.Password)
            .ReturnsForAnyArgs(Task.FromResult(IdentityResult.Failed()));

            var registerCommandHandler =
                new RegisterUserCommandHandler(_mockUserManager, _mockJwtGenerator, _mockEventBus,
                                               _mockUserConfirmationEmail, _mockFailedIdentityResult);

            await registerCommandHandler.Handle(_command, CancellationToken.None);

            _mockFailedIdentityResult.Received()
            .Handle(Arg.Any <AppUser>(), Arg.Any <List <IdentityError> >(), Arg.Any <string>());
        }
Beispiel #26
0
        public async Task GivenAlreadyExistingUser_WhenCallingHandle_ThenResultShouldBeFailure()
        {
            var registerUserCommand = new RegisterUserCommand();

            var mockUserService = new Mock <IUserService>();

            mockUserService.Setup(service => service.GetUserInfo(It.IsAny <CancellationToken>()))
            .ReturnsAsync(new TestUser("test-id", "Test User", "*****@*****.**"));

            var sut = new RegisterUserCommandHandler(mockUserService.Object, Context, Mapper);

            var result = await sut.Handle(registerUserCommand, CancellationToken.None);

            result.IsFailure.Should().BeTrue();
        }
Beispiel #27
0
        public void RegistrationCommand_PresentWeakPassword_ThrowsException()
        {
            // ---- Arrange ----

            const string name         = "test user";
            const string email        = "*****@*****.**";
            const string weakPassword = "******";

            var command = new RegisterUserCommand(email, name, weakPassword);
            var handler = new RegisterUserCommandHandler(_repositoryProviderMock.Object);

            // ---- Act & Assert ----

            Assert.ThrowsAsync <WeakPasswordException>(async() =>
                                                       await handler.Handle(command, CancellationToken.None));
        }
        public void Should_ThrowException_When_CommandIsNull()
        {
            var userRepositoryMock = new Mock <IUserRepository>();
            var roleLookupMock     = new Mock <IRoleLookup>();

            var mapperMock = new Mock <IMapper>();

            mapperMock.Setup(m => m.Map <RegisterUserCommand, User>(It.IsAny <RegisterUserCommand>())).Returns((User)null);

            var target = new RegisterUserCommandHandler(userRepositoryMock.Object, roleLookupMock.Object, mapperMock.Object);

            var command = new RegisterUserCommand();

            Func <Task> func = async() => await target.HandleAsync(command);

            func.ShouldThrow <NullReferenceException>();
        }
Beispiel #29
0
    public async Task GivenValidRegisterUserCommand_WhenCallingHandle_ThenNewUserShouldBeReturned(string newUserId, string newUserDisplayName, string newUserEmailAddress)
    {
        var registerUserCommand = new RegisterUserCommand();

        var mockUserService = Substitute.For <IUserService>();

        mockUserService.GetUserInfo(Arg.Any <CancellationToken>()).Returns(new TestUser(newUserId, newUserDisplayName, newUserEmailAddress));

        var sut = new RegisterUserCommandHandler(mockUserService, Context, Mapper);

        var result = await sut.Handle(registerUserCommand, CancellationToken.None);

        result.Value.Id.Should().BePositive();
        result.Value.ExternalUserId.Should().Be(newUserId);
        result.Value.DisplayName.Should().Be(newUserDisplayName);
        result.Value.EmailAddress.Should().Be(newUserEmailAddress);
    }
Beispiel #30
0
        public void RegistrationCommand_PresentInvalidFormattedEmail_ThrowsException()
        {
            // ---- Arrange ----

            const string invalidEmail = "invalid_email";
            const string name         = "test user";
            const string password     = "******";

            var command = new RegisterUserCommand(invalidEmail, name, password);
            var handler = new RegisterUserCommandHandler(_repositoryProviderMock.Object);

            // ---- Act & Assert

            var exception = Assert.ThrowsAsync <InvalidEmailFormatException>(async() =>
                                                                             await handler.Handle(command, CancellationToken.None));

            Assert.AreEqual(invalidEmail, exception.Email);
        }