public async Task Log_In_User_When_User_Registered()
        {
            var expectedResult = new AccessToken("access-token", 100);

            _userRepositoryMock
            .Setup(x => x.SelectByEmailAsync(
                       It.IsAny <Email>(),
                       It.IsAny <CancellationToken>()))
            .ReturnsAsync(new User(
                              UserId.NewUserId(),
                              new Name("name"),
                              new Email("*****@*****.**"),
                              new Password("cmKaQbB25Yj7qMcco3+tyazcjnMhuctOpV/Qv5/o7XI="),
                              new PasswordSalt("salt")));
            _tokenGeneratorMock
            .Setup(x => x.CreateAccessToken(
                       It.IsAny <string>(),
                       It.IsAny <string>(),
                       It.IsAny <string>(),
                       It.IsAny <string>()))
            .Returns(expectedResult);

            var actualResult = await _sut.Handle(new LoginUserCommand("*****@*****.**", "password"), CancellationToken.None);

            actualResult.Should()
            .BeOfType <LoginUserCommandResult>()
            .Which.AccessToken
            .Should().Be(expectedResult.Token);
        }
Esempio n. 2
0
        public async Task ShouldThrow_InvalidAccountException_OnPassword()
        {
            var request          = FakeRequest();
            var loginMaxAttempts = new LoginMaxAttemptFake().Builder.Generate();
            var user             = new UserFake().Builder
                                   .RuleFor(x => x.Email, f => request.Email)
                                   .Generate();

            var uowGeneralMock = new Mock <IUowGeneral>();

            uowGeneralMock.Setup(x =>
                                 x.UserRepository.FindByEmail(request.Email)).ReturnsAsync(user);
            uowGeneralMock.Setup(x =>
                                 x.LoginMaxAttemptRepository.Find(GeneralConstants.DefaultId)).ReturnsAsync(loginMaxAttempts);
            var passwordServiceMock = new Mock <IPasswordService>();

            passwordServiceMock.Setup(x =>
                                      x.Verify(request.Password, user.Password)).Returns(false);
            var accessTokenServiceMock = new Mock <IAccessTokenService>();
            var refreshTokenService    = new RefreshTokenService(uowGeneralMock.Object);

            var handler = new LoginUserCommandHandler(uowGeneralMock.Object, passwordServiceMock.Object,
                                                      accessTokenServiceMock.Object, refreshTokenService);

            await Assert.ThrowsAsync <InvalidAccountException>(() =>
                                                               handler.Handle(request, default));

            Assert.Equal(1, user.LoginAttempts);
            Assert.Null(user.FindEvent(typeof(MaxLoginAttemptsReached)));
            uowGeneralMock.Verify(x => x.SaveChanges(), Times.Once);
        }
Esempio n. 3
0
        public async Task ShouldThrow_LoginMaxAttemptsReachedException()
        {
            var request          = FakeRequest();
            var loginMaxAttempts = new LoginMaxAttemptFake().Builder.Generate();
            var user             = new UserFake().Builder
                                   .RuleFor(x => x.Email, f => request.Email)
                                   .RuleFor(x => x.LoginAttempts, f => loginMaxAttempts.MaxAttempts + 1)
                                   .Generate();

            var uowGeneralMock = new Mock <IUowGeneral>();

            uowGeneralMock.Setup(x =>
                                 x.UserRepository.FindByEmail(request.Email)).ReturnsAsync(user);
            uowGeneralMock.Setup(x =>
                                 x.LoginMaxAttemptRepository.Find(GeneralConstants.DefaultId)).ReturnsAsync(loginMaxAttempts);
            var passwordServiceMock    = new Mock <IPasswordService>();
            var accessTokenServiceMock = new Mock <IAccessTokenService>();
            var refreshTokenService    = new RefreshTokenService(uowGeneralMock.Object);

            var handler = new LoginUserCommandHandler(uowGeneralMock.Object, passwordServiceMock.Object,
                                                      accessTokenServiceMock.Object, refreshTokenService);

            await Assert.ThrowsAsync <LoginMaxAttemptsReachedException>(() =>
                                                                        handler.Handle(request, default));
        }
Esempio n. 4
0
        public async Task Should_LoginUser()
        {
            var request          = FakeRequest();
            var loginMaxAttempts = new LoginMaxAttemptFake().Builder.Generate();
            var user             = new UserFake().Builder
                                   .RuleFor(x => x.Email, f => request.Email)
                                   .Generate();

            var uowGeneralMock = new Mock <IUowGeneral>();

            uowGeneralMock.Setup(x =>
                                 x.UserRepository.FindByEmail(request.Email)).ReturnsAsync(user);
            uowGeneralMock.Setup(x =>
                                 x.LoginMaxAttemptRepository.Find(GeneralConstants.DefaultId)).ReturnsAsync(loginMaxAttempts);
            uowGeneralMock.Setup(x =>
                                 x.RefreshTokenRepository.Create(It.IsAny <RefreshToken>())).ReturnsAsync(It.IsAny <RefreshToken>());
            var passwordServiceMock = new Mock <IPasswordService>();

            passwordServiceMock.Setup(x =>
                                      x.Verify(request.Password, user.Password)).Returns(true);
            var accessTokenServiceMock = new Mock <IAccessTokenService>();
            var refreshTokenService    = new RefreshTokenService(uowGeneralMock.Object);

            var handler = new LoginUserCommandHandler(uowGeneralMock.Object, passwordServiceMock.Object,
                                                      accessTokenServiceMock.Object, refreshTokenService);

            var response = await handler.Handle(request, default);

            Assert.NotNull(response);
            Assert.NotNull(user.FindEvent(typeof(UserLogged)));
            accessTokenServiceMock.Verify(x => x.GetAccessToken(user), Times.Once);
            uowGeneralMock.Verify(x => x.UserRepository.Update(user), Times.Once);
            uowGeneralMock.Verify(x => x.SaveChanges(), Times.Once);
        }
        public async Task InputDataIsOk_Executed_ReturnLoginUserViewModel()
        {
            //Arrange
            var loginUserCommand = new LoginUserCommand
            {
                Email    = "*****@*****.**",
                Password = "******"
            };

            var user  = new User("Nome de teste", loginUserCommand.Email, Convert.ToDateTime("15/12/1993"), loginUserCommand.Password, "client");
            var token = "adsadsa5d56asda564das564da5s64d56a4ds456";

            var authServiceMock    = new Mock <IAuthService>();
            var userRepositoryMock = new Mock <IUserRepository>();

            var loginUserCommandHandler = new LoginUserCommandHandler(authServiceMock.Object, userRepositoryMock.Object);

            authServiceMock.Setup(u => u.ComputeSha256Hash(loginUserCommand.Password)).Returns(loginUserCommand.Password);
            authServiceMock.Setup(u => u.GenerateJwtToken(loginUserCommand.Email, user.Role)).Returns(token);
            userRepositoryMock.Setup(u => u.LoginAsync(loginUserCommand.Email, loginUserCommand.Password).Result).Returns(user);

            //Act
            var loginUserViewModel = await loginUserCommandHandler.Handle(loginUserCommand, new CancellationToken());

            //Assert
            Assert.NotNull(loginUserViewModel);

            userRepositoryMock.Verify(u => u.LoginAsync(It.IsAny <string>(), It.IsAny <string>()), Times.Once);
            authServiceMock.Verify(a => a.GenerateJwtToken(It.IsAny <string>(), It.IsAny <string>()), Times.Once);
        }
        public async Task InputDataIsok_Executed_LoginUserViewModel()
        {
            var fixture        = new Fixture();
            var userRepository = new Mock <IUserRepository>();
            var authService    = new Mock <IAuthService>();

            var user = new User(1, "abc", "*****@*****.**", "123", "admin");

            var userEmail    = user.Email;
            var userPassword = user.Password;

            userRepository.Setup(u => u.GetUserByEmailAndPasswordAsync(user.Email, user.Password))
            .Returns(ConverUserInTaskUser(user));

            authService.Setup(u => u.ComputeSha256Hash(user.Password)).Returns(user.Password);
            authService.Setup(u => u.GenerateJwtToken(user.Email, user.Role)).Returns("asdasfsdfkjldhl");

            var loginUserCommand = new LoginUserCommand(userEmail, userPassword);

            var loginUserCommandHandler = new LoginUserCommandHandler(authService.Object, userRepository.Object);

            var userViewModel = await loginUserCommandHandler.Handle(loginUserCommand, new System.Threading.CancellationToken());

            Assert.IsType <LoginUserViewModel>(userViewModel);
            Assert.NotNull(userViewModel.Token);
            Assert.NotEmpty(userViewModel.Token);

            userRepository.Verify(g => g.GetUserByEmailAndPasswordAsync(userEmail, userPassword), Times.Once);
            authService.Verify(g => g.ComputeSha256Hash(user.Password), Times.Once);
            authService.Verify(g => g.GenerateJwtToken(user.Email, user.Role), Times.Once);
        }
Esempio n. 7
0
        public async void Login_UnauthorizedAccess(string userName, string password)
        {
            //ARRANGE
            var fakeUserManager = new Mock <FakeUserManager>();

            _context.Users.AddRange(GetFakeData().AsQueryable());
            _context.SaveChanges();
            var userToCheck = await _context.Users.FirstOrDefaultAsync(u => u.UserName == userName);

            fakeUserManager.Setup(x => x.Users)
            .Returns(_context.Users);

            fakeUserManager.Setup(x => x.CheckPasswordAsync(userToCheck, "12345678"))
            .ReturnsAsync(true);
            fakeUserManager.Setup(x => x.GetRolesAsync(userToCheck)).ReturnsAsync(new List <string> {
                "Admin", "Member", "Moderator"
            });

            var mediator = new Mock <IMediator>();

            LoginUserCommandHandler loginHandler = new LoginUserCommandHandler(_context, mediator.Object, _mapper,
                                                                               _configuration, fakeUserManager.Object);

            await Assert.ThrowsAsync <UnauthorizedAccessException>(() => loginHandler.Handle(new UserForLoginDto {
                Username = userName, Password = password
            }, new System.Threading.CancellationToken()));
        }
Esempio n. 8
0
        public async void CanLoginUser()
        {
            var command = new LoginUserCommand
            {
                EmailAddress = "*****@*****.**",
                Password     = "******",
                RememberMe   = false
            };
            var handler = new LoginUserCommandHandler(_signInManager);
            var result  = await handler.Handle(command);

            Assert.True(result.Success);
        }
Esempio n. 9
0
        public async void CanFailLoginWithBadPassword()
        {
            var command = new LoginUserCommand()
            {
                EmailAddress = "*****@*****.**",
                Password     = "******",
                RememberMe   = false
            };
            var handler = new LoginUserCommandHandler(_signInManager);
            var result  = await handler.Handle(command);

            Assert.False(result.Success);
            Assert.True(result.Errors.Count > 0, "No errors present in the login result");
        }
Esempio n. 10
0
        public async Task ShouldThrow_InvalidAccountException_OnNotFoundUser()
        {
            var request = FakeRequest();

            var uowGeneralMock = new Mock <IUowGeneral>();

            uowGeneralMock.Setup(x =>
                                 x.UserRepository.FindByEmail(request.Email)).ReturnsAsync(default(User));
            var passwordServiceMock    = new Mock <IPasswordService>();
            var accessTokenServiceMock = new Mock <IAccessTokenService>();
            var refreshTokenService    = new RefreshTokenService(uowGeneralMock.Object);

            var handler = new LoginUserCommandHandler(uowGeneralMock.Object, passwordServiceMock.Object,
                                                      accessTokenServiceMock.Object, refreshTokenService);

            await Assert.ThrowsAsync <InvalidAccountException>(() =>
                                                               handler.Handle(request, default));
        }
Esempio n. 11
0
        public async Task ShouldThrow_InvalidAccountException_OnDisabledAccount()
        {
            var request = FakeRequest();
            var user    = new UserFake().Builder
                          .RuleFor(x => x.DisabledAccountAt, f => f.Date.Recent())
                          .Generate();

            var uowGeneralMock = new Mock <IUowGeneral>();

            uowGeneralMock.Setup(x =>
                                 x.UserRepository.FindByEmail(request.Email)).ReturnsAsync(user);
            var passwordServiceMock    = new Mock <IPasswordService>();
            var accessTokenServiceMock = new Mock <IAccessTokenService>();
            var refreshTokenService    = new RefreshTokenService(uowGeneralMock.Object);

            var handler = new LoginUserCommandHandler(uowGeneralMock.Object, passwordServiceMock.Object,
                                                      accessTokenServiceMock.Object, refreshTokenService);

            await Assert.ThrowsAsync <InvalidAccountException>(() =>
                                                               handler.Handle(request, default));
        }
        public async Task GivenValidUserRequest_WhenThePasswordDoesNotMatch_ThrowsApiExceptionForBadRequest()
        {
            // Arrange
            var userLoginCommand = new LoginUserCommand
            {
                User = new UserLoginDto
                {
                    Email    = "*****@*****.**",
                    Password = "******"
                }
            };

            // Act
            var command = new LoginUserCommandHandler(UserManager, Context, TokenService, _logger, Mapper);

            // Assert
            await Should.ThrowAsync <ConduitApiException>(async() =>
            {
                await command.Handle(userLoginCommand, CancellationToken.None);
            });
        }
        public async Task PasswordInvalid_Executed_ReturnUnitValue()
        {
            var fixture        = new Fixture();
            var userRepository = new Mock <IUserRepository>();
            var authService    = new Mock <IAuthService>();

            var user = new User(1, "abc", "*****@*****.**", "123", "admin");

            var userEmail    = "*****@*****.**";
            var userPassword = "******";

            userRepository.Setup(u => u.GetUserByEmailAndPasswordAsync(userEmail, userPassword))
            .Returns(ConverUserInTaskUser(new User(2, "", "", "", "")));

            authService.Setup(u => u.ComputeSha256Hash(It.IsAny <string>()))
            .Returns((string pass) =>
            {
                if (pass == "123")
                {
                    return("123");
                }
                else
                {
                    return("23333");
                }
            });


            var loginUserCommand = new LoginUserCommand(userEmail, userPassword);

            var loginUserCommandHandler = new LoginUserCommandHandler(authService.Object, userRepository.Object);

            var loginResult = await loginUserCommandHandler.Handle(loginUserCommand, new System.Threading.CancellationToken());

            Assert.Null(loginResult);

            userRepository.Verify(g => g.GetUserByEmailAndPasswordAsync(It.IsAny <string>(), It.IsAny <string>()), Times.Once);
            authService.Verify(g => g.ComputeSha256Hash(It.IsAny <string>()), Times.Once);
            authService.Verify(g => g.GenerateJwtToken(user.Email, user.Role), Times.Never);
        }
        public async Task GivenValidUserRequest_WhenTheUserExists_ReturnsProperUserViewModelResponse()
        {
            // Arrange
            var userLoginCommand = new LoginUserCommand
            {
                User = new UserLoginDto
                {
                    Email    = "*****@*****.**",
                    Password = "******"
                }
            };

            // Act
            var command = new LoginUserCommandHandler(UserManager, Context, TokenService, _logger, Mapper);
            var result  = await command.Handle(userLoginCommand, CancellationToken.None);

            // Assert
            result.ShouldNotBeNull();
            result.User.ShouldNotBeNull();
            result.User.Email.ShouldBe(userLoginCommand.User.Email);
            result.User.Username.ShouldBe("test.user");
        }
Esempio n. 15
0
        public async Task Handle_should_return_user_details()
        {
            //Arrange
            var query = new LoginUserCommand()
            {
                Email      = "*****@*****.**",
                SceretKey  = "SiemensBangalore",
                TenantName = "Siemens",
                Password   = "******",
                JWTAuth    = new MockJwtTokens()
            };

            //ACT
            var response = await _loginUserCommandHandler.Handle(query, new System.Threading.CancellationToken());

            //Assert
            Assert.IsInstanceOfType(response, typeof(SuccessResponseDTO <LoginResponseModel>));
            Assert.AreEqual(response.StatusInfo.Status, Constants.Sucessfully_logged_in);
        }