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();
                }
            }
        }
예제 #2
0
        public void ThenTheCommandIsHandledAndValidatorCalled()
        {
            //Arrange
            _registerUserCommandValidator.Setup(x => x.ValidateAsync(It.IsAny <RegisterUserCommand>())).ReturnsAsync(new ValidationResult {
                ValidationDictionary = new Dictionary <string, string> {
                    { "MyError", "Some error has happened" }
                }
            });

            //Act
            var actual = Assert.ThrowsAsync <InvalidRequestException>(async() => await _registerUserCommandHandler.Handle(new RegisterUserCommand()));

            //Assert
            _registerUserCommandValidator.Verify(x => x.ValidateAsync(It.IsAny <RegisterUserCommand>()));
            Assert.Contains(new KeyValuePair <string, string>("MyError", "Some error has happened"), actual.ErrorMessages);
        }
예제 #3
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();
                }
            }
        }
        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);
        }
예제 #5
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 void Handle(RegisterUserCommand command)
 {
     command.User.Salt     = HashPassword.GenerateSalt(50);
     command.User.Password = HashPassword.GenerateHash(command.User.Password, command.User.Salt);
     using (_unitOfWork = new UnitOfWork())
     {
         _handler.Handle(command);
     }
 }
예제 #7
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();
    }
예제 #8
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());
    }
예제 #9
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));
        }
예제 #10
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>());
        }
예제 #11
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);
        }
예제 #12
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>());
        }
예제 #13
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();
    }
예제 #14
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();
        }
        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);
        }
예제 #16
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>());
        }
        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 Handler_Register()
        {
            var registerUser = new User {
                Email = "*****@*****.**", FullName = "test test"
            };

            _command = new RegisterUserCommand
            {
                Email    = registerUser.Email,
                FullName = registerUser.FullName,
                Password = "******"
            };
            var result = await _registerUserCommandHandler.Handle(_command, CancellationToken.None);

            result.Message.Should().Be(Messages.Added);
        }
예제 #19
0
        public async Task Handler_Register()
        {
            var registerUser = new User();

            registerUser.Email    = "*****@*****.**";
            registerUser.FullName = "test test";
            command = new RegisterUser.Command
            {
                Email    = registerUser.Email,
                FullName = registerUser.FullName,
                Password = "******"
            };
            var result = await registerUserCommandHandler.Handle(command, new System.Threading.CancellationToken());

            Assert.That(result.Message, Is.EqualTo(Messages.Added));
        }
예제 #20
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));
        }
예제 #21
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);
    }
예제 #22
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);
        }
예제 #23
0
        public void RegistrationCommand_PresentInvalidFormattedName_ThrowsException()
        {
            // ---- Arrange ----

            const string badName  = "";
            const string email    = "*****@*****.**";
            const string password = "******";

            var command = new RegisterUserCommand(email, badName, password);
            var handler = new RegisterUserCommandHandler(_repositoryProviderMock.Object);

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

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

            Assert.AreEqual(badName, exception.Name);
        }
        public async Task Should_pass_user_registration_result_from_user_manager_to_caller()
        {
            // Act
            var expectedResult = Result.Success();

            var userManagerMock = new Mock <IUserManager>();

            userManagerMock
            .Setup(mock => mock.CreateAsync("*****@*****.**", "P@ssw0rd"))
            .ReturnsAsync(expectedResult);

            var handler = new RegisterUserCommandHandler(userManagerMock.Object);

            // Act
            var actualResult = await handler.Handle(new RegisterUserCommand("*****@*****.**", "P@ssw0rd"));

            // Assert
            actualResult.Result.Should().Be(expectedResult);
        }
        public async Task Should_Raise_UserRegisteredEvent_When_UserRegistered()
        {
            //Arrange
            var mediatorMock = new Mock <IMediator>();
            Mock <IUserManagerService>  userManagerService  = new Mock <IUserManagerService>();
            Mock <IIdentityDataContext> identityDataContext = new Mock <IIdentityDataContext>();

            var applicationUser = new ApplicationUser()
            {
                Email        = String.Empty,
                UserName     = String.Empty,
                FirstName    = String.Empty,
                LastName     = String.Empty,
                Id           = 1,
                PasswordHash = String.Empty
            };

            userManagerService.Setup(r => r.CreateUser(It.IsAny <ApplicationUser>(), It.IsAny <String>()))
            .Returns(Task.FromResult(applicationUser));


            mediatorMock.Setup(p => p.Publish(It.IsAny <UserRegisteredEvent>(), It.IsAny <CancellationToken>()))
            .Returns(Task.CompletedTask);

            var sut = new RegisterUserCommandHandler(identityDataContext.Object, _mapper, _logger,
                                                     mediatorMock.Object, userManagerService.Object);

            //Act
            await sut.Handle(new RegisterUserCommand(
                                 firstName : String.Empty,
                                 lastName : String.Empty,
                                 password : String.Empty,
                                 email : String.Empty,
                                 dateOfBirth : DateTime.Now,
                                 userName : String.Empty
                                 ), It.IsAny <CancellationToken>());

            //Assert
            mediatorMock.Verify(m => m.Publish(It.Is <UserRegisteredEvent>(cc => cc.Id == applicationUser.Id),
                                               It.IsAny <CancellationToken>()), Times.Once);
        }
예제 #26
0
        public void Handle_GivenValidRequest_ShouldRaiseUserRegisteredNotification()
        {
            // Arrange
            var mediatorMock = new Mock <IMediator>();
            var sut          = new RegisterUserCommandHandler(_context, mediatorMock.Object);

            var cmd = new RegisterUserCommand()
            {
                Email           = "*****@*****.**",
                FirstName       = "Petar",
                IsBusinessOwner = false,
                LastName        = "Peric",
                Username        = "******"
            };

            // Act
            var result = sut.Handle(cmd, CancellationToken.None);

            // Assert
            mediatorMock.Verify(m => m.Publish(It.Is <UserRegistered>(cc => cc.Data.Username == cmd.Email), It.IsAny <CancellationToken>()), Times.Once);
        }
예제 #27
0
        public void RegistrationCommand_PresentAlreadyExistsEmail_ThrowsException()
        {
            // ---- Arrange ----
            const string name     = "test user";
            const string email    = "*****@*****.**";
            const string password = "******";

            _authRepositoryMock.Setup(r => r.IsUserIdentityExists(email))
            .ReturnsAsync(true);

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

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

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

            _authRepositoryMock.Verify(r => r.IsUserIdentityExists(email), Times.Once);
            Assert.AreEqual(email, exception.Email);
        }
        public void Handle_OnValidData_ReturnsProperMessage()
        {
            var userServiceMock = new Mock <IUserService>();

            userServiceMock
            .Setup(x => x.RegisterAsync(It.IsAny <RegisterUserCommand>()))
            .Returns(Task.FromResult("some text"));

            var sut = new RegisterUserCommandHandler(userServiceMock.Object);

            var registerCommand = new RegisterUserCommand
            {
                Email    = "*****@*****.**",
                Password = "******"
            };

            var result = sut.Handle(registerCommand, new CancellationToken());

            result.Should().NotBeNull();
            result.Result.Message.Should().NotBeNull();
            result.Result.Message.Should().Be("some text");
        }
        public async Task Should_Throws_DuplicateException_When_User_Already_Exists()
        {
            //Arrange
            var mediatorMock = new Mock <IMediator>();
            Mock <IUserManagerService>  userManagerService  = new Mock <IUserManagerService>();
            Mock <IIdentityDataContext> identityDataContext = new Mock <IIdentityDataContext>();

            var applicationUser = new ApplicationUser()
            {
                Email        = String.Empty,
                UserName     = String.Empty,
                FirstName    = String.Empty,
                LastName     = String.Empty,
                Id           = 1,
                PasswordHash = String.Empty
            };

            userManagerService.Setup(r => r.CreateUser(It.IsAny <ApplicationUser>(), It.IsAny <String>()))
            .Throws <DuplicateException>();

            mediatorMock.Setup(p => p.Publish(It.IsAny <UserRegisteredEvent>(), It.IsAny <CancellationToken>()))
            .Returns(Task.CompletedTask);

            var sut = new RegisterUserCommandHandler(identityDataContext.Object, _mapper, _logger,
                                                     mediatorMock.Object, userManagerService.Object);

            //Act/Assert
            await Assert.ThrowsAsync <DuplicateException>(async() =>
            {
                await sut.Handle(new RegisterUserCommand(
                                     firstName: String.Empty,
                                     lastName: String.Empty,
                                     password: String.Empty,
                                     email: String.Empty,
                                     dateOfBirth: DateTime.Now,
                                     userName: String.Empty
                                     ), It.IsAny <CancellationToken>());
            });
        }
        public async Task GivenNewUser_Handle_ShouldReturnNewRegisteredUser()
        {
            var registerUserCommand = new RegisterUserCommand();

            const string expectedNewUserId           = "new-id";
            const string expectedNewUserDisplayName  = "New User";
            const string expectedNewUserEmailAddress = "*****@*****.**";

            var mockUserService = new Mock <IUserService>();

            mockUserService.Setup(service => service.GetUserInfo(It.IsAny <CancellationToken>()))
            .ReturnsAsync(new TestUser(expectedNewUserId, expectedNewUserDisplayName, expectedNewUserEmailAddress));

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

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

            result.Value.Id.ShouldBeGreaterThan(0);
            result.Value.DisplayName.ShouldBe(expectedNewUserDisplayName);
            result.Value.EmailAddress.ShouldBe(expectedNewUserEmailAddress);
            result.Value.ExternalUserId.ShouldBe(expectedNewUserId);
        }