Example #1
0
        public async Task <Result <UserAndTokenDto> > Handle(LoginUserQuery request, CancellationToken cancellationToken)
        {
            var user = await _userManager.FindByEmailAsync(request.Email);

            if (user is null)
            {
                return(Result <UserAndTokenDto> .Failure("Unable to find user.", true));
            }

            var loginUser = await _signInManager.CheckPasswordSignInAsync(user, request.Password, false);

            if (!loginUser.Succeeded)
            {
                return(Result <UserAndTokenDto> .Failure("Failed to login user.", true));
            }

            var refreshToken = await CreateAndSaveRefreshToken(user);

            if (refreshToken is null)
            {
                return(Result <UserAndTokenDto> .Failure("Unable to save new refresh token."));
            }

            return(FinishLogin(user, refreshToken));
        }
Example #2
0
        public async Task <IActionResult> SignIn([FromBody] SignInViewModel viewModel)
        {
            var query  = new LoginUserQuery(viewModel.Email, viewModel.Password);
            var result = await _commandQueryDispatcherDecorator.DispatchAsync <LoginUserQuery, LoggedUserDto>(query);

            return(Ok(_mapper.Map <LoggedUserViewModel>(result)));
        }
Example #3
0
        public async Task <Result <LoginUserFoundDTO> > Handle(LoginUserQuery request, CancellationToken cancellationToken)
        {
            var login    = Login.Create(request.Login);
            var password = Password.Create(request.Password, _passwordHasher);
            var result   = Result.Combine(login, password);

            if (result.Failure)
            {
                _logger.Error(result.Error);
                throw new GroceryException(result.Error);
            }
            var memberShip = new MemberShip(login.Value, password.Value);
            var user       = await _memberShipRepository.GetMemberShipByLoginPassword(memberShip.Login.LoginValue, memberShip.Password.PasswordValue);

            await _domainEventDispatcher.DispatchAsync(memberShip.DomainEvents.ToArray());

            if (user is null)
            {
                _logger.Error(nameof(Parameters.INVALID_USER), DateTime.Now);
                return(Result.Fail <LoginUserFoundDTO>(nameof(Parameters.INVALID_USER)));
            }
            var loggedUser = _mapper.Map <LoginUserFoundDTO>(user);

            loggedUser.JwtDTO = _jwtGenerator.Generate(user);
            _logger.Information($"User logged {loggedUser.MemberShipId} {DateTime.Now.ToStringDate()}");
            return(Result.Ok(loggedUser));
        }
Example #4
0
        public async Task ShouldLoginUser()
        {
            //arrange
            var command = new RegisterUserCommand()
            {
                Username = "******",
                Email    = "scott@localhost",
                Password = "******"
            };

            await SendAsync(command);

            var query = new LoginUserQuery()
            {
                Email    = "scott@localhost",
                Password = "******"
            };

            //act
            var loginUser = await SendAsync(query);

            //assert
            loginUser.Username.Should().Be(command.Username);
            loginUser.Image.Should().BeNull();
        }
Example #5
0
        public async Task <IActionResult> LoginUser(LoginUserDTO userDTO)
        {
            var loginUserQuery = new LoginUserQuery(userDTO.Login, userDTO.Password);
            var result         = await _mediatr.Send(loginUserQuery);

            return(result.Failure ? NotFound(result.Error) : (IActionResult)Ok(result.Value));
        }
Example #6
0
        public async Task Handler_Login()
        {
            var user = DataHelper.GetUser("test");

            HashingHelper.CreatePasswordHash("123456", out byte[] passwordSalt, out byte[] passwordHash);
            user.PasswordSalt = passwordSalt;
            user.PasswordHash = passwordHash;
            _userRepository.
            Setup(x => x.GetAsync(It.IsAny <Expression <Func <User, bool> > >())).Returns(() => Task.FromResult(user));


            _userRepository.Setup(x => x.GetClaims(It.IsAny <int>()))
            .Returns(new List <OperationClaim>()
            {
                new OperationClaim()
                {
                    Id = 1, Name = "test"
                }
            });
            loginUserQuery = new LoginUserQuery
            {
                Email    = user.Email,
                Password = "******"
            };

            var result = await loginUserQueryHandler.Handle(loginUserQuery, new System.Threading.CancellationToken());

            Assert.That(result.Success, Is.True);
        }
Example #7
0
        public void NullPassword_ShouldHaveError()
        {
            var query = new LoginUserQuery {
                Password = null
            };

            _sut.ShouldHaveValidationErrorFor(x => x.Password, query);
        }
Example #8
0
        public void InvalidEmail_ShouldHaveError()
        {
            var query = new LoginUserQuery {
                Email = "invalidEmail"
            };

            _sut.ShouldHaveValidationErrorFor(x => x.Email, query);
        }
Example #9
0
        public void EmptyOrNullEmail_ShouldHaveError(string email)
        {
            var query = new LoginUserQuery {
                Email = email
            };

            _sut.ShouldHaveValidationErrorFor(x => x.Email, query);
        }
Example #10
0
        public async Task WhenIEnterMyValidCredentials()
        {
            _query = new LoginUserQuery {
                Email = "*****@*****.**", Password = "******"
            };

            _response = await _client.PostAsync(BaseUrl, Utilities.GetRequestContent(_query));
        }
Example #11
0
        public async Task WhenIEnterAnInvalidEmailAddressLike(string invalidEmail)
        {
            _query = new LoginUserQuery {
                Email = invalidEmail, Password = "******"
            };

            _response = await _client.PostAsync(BaseUrl, Utilities.GetRequestContent(_query));
        }
Example #12
0
        public async Task WhenIEnterABadEmailAddressOrABadPassword()
        {
            _query = new LoginUserQuery {
                Email = "*****@*****.**", Password = "******"
            };

            _response = await _client.PostAsync(BaseUrl, Utilities.GetRequestContent(_query));
        }
Example #13
0
        public async Task WhenIEnterAnEmptyOrANullAddress(string email)
        {
            _query = new LoginUserQuery {
                Email = email, Password = "******"
            };

            _response = await _client.PostAsync(BaseUrl, Utilities.GetRequestContent(_query));
        }
Example #14
0
        public async Task WhenIEnterAnEmptyOrANull(string password)
        {
            _query = new LoginUserQuery {
                Email = "*****@*****.**", Password = password
            };

            _response = await _client.PostAsync(BaseUrl, Utilities.GetRequestContent(_query));
        }
Example #15
0
        public void ValidLoginAndPassword_ShouldNotHaveErrors()
        {
            var query = new LoginUserQuery {
                Email = "*****@*****.**", Password = "******"
            };

            _sut.ShouldNotHaveValidationErrorFor(x => x.Email, query);
            _sut.ShouldNotHaveValidationErrorFor(x => x.Password, query);
        }
Example #16
0
        public async Task ThenLoginWithTheNewPasswordShouldBeSuccessful()
        {
            var query = new LoginUserQuery {
                Email = _user.Email, Password = _command.NewPassword
            };

            _response = await _client.PostAsync("/api/auth/login", Utilities.GetRequestContent(query));

            _response.EnsureSuccessStatusCode();
        }
Example #17
0
        public IActionResult Login([FromQuery] LoginUserQuery query)
        {
            var user = _mediator.Send(query);

            if (user.Result == null)
            {
                return(BadRequest("Wrong email or password"));
            }
            return(Ok(user));
        }
Example #18
0
        public async Task When_User_Not_Exist_Throw_Exception(LoginUserQuery model)
        {
            //Arrange
            User user = null;

            _userRepository.Setup(x => x.GetByEmail(It.IsAny <string>())).ReturnsAsync(user);

            //Assert
            await Assert.ThrowsAsync <AppException>(() => _sut.Handle(model, default));
        }
        public async Task <IActionResult> Login([FromBody] LoginUserQuery loginModel)
        {
            var result = await Mediator.Send(loginModel);

            if (result.Success)
            {
                return(Ok(result));
            }
            return(Unauthorized(result.Message));
        }
Example #20
0
        public async Task <IActionResult> Login([FromBody] LoginUserQuery loginUser)
        {
            var result = await _mediator.Send(loginUser);

            if (result.Success)
            {
                return(Ok(result));
            }

            return(BadRequest(result));
        }
        public async Task <IActionResult> Login(LoginUserQuery query)
        {
            var User = await Mediator.Send(query);

            if (User != null)
            {
                #region Cookie Authentication
                var claims = new List <Claim>
                {
                    new Claim(ClaimTypes.NameIdentifier, User.ID.ToString()),
                    new Claim(ClaimTypes.Name, User.FullName),
                    new Claim(ClaimTypes.Email, User.EmailAddress),
                    new Claim(ClaimTypes.Role, User.UserType.ToString()),
                };

                var claimsIdentity = new ClaimsIdentity(
                    claims, CookieAuthenticationDefaults.AuthenticationScheme);

                var authProperties = new AuthenticationProperties
                {
                    //AllowRefresh = <bool>,
                    // Refreshing the authentication session should be allowed.

                    //ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(10),
                    // The time at which the authentication ticket expires. A
                    // value set here overrides the ExpireTimeSpan option of
                    // CookieAuthenticationOptions set with AddCookie.

                    //IsPersistent = true,
                    // Whether the authentication session is persisted across
                    // multiple requests. When used with cookies, controls
                    // whether the cookie's lifetime is absolute (matching the
                    // lifetime of the authentication ticket) or session-based.

                    //IssuedUtc = <DateTimeOffset>,
                    // The time at which the authentication ticket was issued.

                    //RedirectUri = <string>
                    // The full path or absolute URI to be used as an http
                    // redirect response value.
                };

                await HttpContext.SignInAsync(
                    CookieAuthenticationDefaults.AuthenticationScheme,
                    new ClaimsPrincipal(claimsIdentity),
                    authProperties);

                #endregion

                return(RedirectToAction("Index", "Home"));
            }

            return(View("Index", query));
        }
        public async Task <ActionResult> Login(BuildingUserView buildingUser)
        {
            var query  = new LoginUserQuery(buildingUser);
            var result = await _mediator.Send(query);

            if (result)
            {
                return(RedirectToAction(nameof(Index), "BuildingActivities"));
            }

            return(View(nameof(Login), buildingUser));
        }
Example #23
0
        public async Task When_User_Enter_Invalid_Password_Throw_Exception(LoginUserQuery model)
        {
            //Arrange
            _passwordManager.Setup(x => x.CreatePasswordHash(It.IsAny <string>())).Returns(new Tuple <byte[], byte[]>(CreateString(), CreateString()));
            _passwordManager.Setup(x => x.VerifyPassword(It.IsAny <string>(), It.IsAny <byte[]>(), It.IsAny <byte[]>())).Returns(false);
            var user = CreateUser("*****@*****.**", _passwordManager.Object);

            _userRepository.Setup(x => x.GetByEmail(It.IsAny <string>())).ReturnsAsync(user);

            //Assert
            await Assert.ThrowsAsync <AppException>(() => _sut.Handle(model, default));
        }
        public async Task <IActionResult> Authentication(LoginUserQuery loginUserQuery)
        {
            try
            {
                var userToken = await Mediator.Send(loginUserQuery);

                return(Ok(userToken));
            }
            catch (ApplicationException e)
            {
                return(NotFound());
            }
        }
Example #25
0
        public LoginUserQueryHandlerTests(AuthenticationFixture fixture)
        {
            _mockUserManager  = fixture.UserManager;
            _mockJwtGenerator = fixture.JwtGenerator;
            _mockEventBus     = fixture.EventBus;
            _user             = fixture.TestUser;

            _query = new LoginUserQuery
            {
                Email    = "*****@*****.**",
                Password = "******"
            };
        }
Example #26
0
        public void ShouldHaveErrorWhenPasswordNotProvided()
        {
            //arrange
            var query = new LoginUserQuery()
            {
                Email = "scott@localhost"
            };

            //act

            //assert
            FluentActions.Invoking(() =>
                                   SendAsync(query)).Should().ThrowAsync <ValidationException>();
        }
Example #27
0
        public void ShouldHaveErrorWhenEmailNotProvided()
        {
            //arrange
            var query = new LoginUserQuery()
            {
                Password = "******"
            };

            //act

            //assert
            FluentActions.Invoking(() =>
                                   SendAsync(query)).Should().ThrowAsync <ValidationException>();
        }
        public void GivenLoginPostMethod_WhenReceivesCorrectQuery_ThenMediatorSendMethodShouldFire()
        {
            var loginQuery = new LoginUserQuery
            {
                Email    = "*****@*****.**",
                Password = "******"
            };

            var authenticationController = new AuthenticationController(_mockMediator, _mockTokenHandler);

            authenticationController.Login(loginQuery);

            _mockMediator.Received().Send(loginQuery);
        }
        public void SetUp()
        {
            _service       = new Mock <ILoginUserService>();
            _commonService = new Mock <ICommonService>();
            _unitOfWork    = new Mock <IUnitOfWork>();
            _sut           = new LoginUserQueryHandler(_service.Object, _commonService.Object, _unitOfWork.Object);
            _query         = new LoginUserQuery {
                Email = "email", Password = "******"
            };

            _user = new User("email", "organizationId");
            _service.Setup(x => x.GetUserByEmail(_query.Email, default))
            .ReturnsAsync(_user);
        }
Example #30
0
        public async Task ShouldReturnExistingUserOnValidCandidateIdAndPassword()
        {
            ILogger logger = new ConsoleLogger();
            LoginRequestValidator validator      = new LoginRequestValidator();
            PasswordHasher        passwordHasher = new PasswordHasher();
            LoginDto loginDto = new LoginDto()
            {
                CandidateId = "aaabbb000", Password = "******"
            };

            var query  = new LoginUserQuery(logger, validator, DbContext.Object, passwordHasher);
            var result = await query.Execute(loginDto);

            Assert.AreEqual(result, GetUserCollection()[0]);
        }