public AuthenticateResponseDto Authenticate(UserCredentialsViewModel credentialsViewModel)
        {
            using (AuthenticationExampleDbContext context = new AuthenticationExampleDbContext())
            {
                UserDto userDto = new UserCredentialsValidator(context).CredentialsIsValid(new UserCredentialsDto
                {
                    UserName = credentialsViewModel.UserName,
                    Password = credentialsViewModel.Password
                });

                if (userDto != null)
                {
                    return(new AuthenticateResponseDto
                    {
                        SecureToken = new TokenBuilder(context).TokenBuild(new LoggedUserDto
                        {
                            UserId = userDto.Id,
                            UserName = userDto.UserName,
                            Password = credentialsViewModel.Password
                        })
                    });
                }
            }

            throw new WebFaultException <RequestErrorDto>(
                      new RequestErrorDto
            {
                StatusCode = (int)HttpStatusCode.Forbidden,
                Reason     = "Authentication Error!",
                Details    = "Username/ password pair is incorrect!"
            }, HttpStatusCode.Unauthorized);
        }
Example #2
0
        public async Task <IActionResult> Login(UserCredentialsViewModel model)
        {
            var user = await _userManager.FindByEmailAsync(model.Email);

            if (user != null && await _userManager.CheckPasswordAsync(user, model.Password))
            {
                var admin = adminService.GetAdminByIdentityId(user.Id);
                if (admin == null)
                {
                    TempData["ErrorMessage"] = "Email ou mot de passe incorrect.";
                    return(View());
                }

                if (!admin.HasValidatedEmail)
                {
                    TempData["ErrorMessage"] = "Votre compte n'est encore activé. Vérifiez votre boite Emails.";
                    return(View());
                }
                HttpContext.Session.SetInt32("AdminId", admin.Id);
                return(RedirectToAction("Index", "Home"));
            }

            TempData["ErrorMessage"] = "Email ou mot de passe incorrect.";
            return(View());
        }
Example #3
0
        public async Task Post_ShouldSuccess()
        {
            var client = this.factory.CreateClient();

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
                "Bearer",
                await AuthenticationUtilities.GetTestUserAccessTokenAsync(client));

            MessengerContext context = this.factory.Server.Host.Services.GetService(typeof(MessengerContext))
                                       as MessengerContext;

            User user = this.GenerateUsers(1).Single();

            var requestBody = new UserCredentialsViewModel {
                Password = "******", UserName = user.UserName, Name = user.Name
            };
            var requestContent = new StringContent(JsonConvert.SerializeObject(requestBody), Encoding.UTF8, "application/json");
            var response       = await client.PostAsync($"/api/users", requestContent);

            response.EnsureSuccessStatusCode();

            UserManager <User> userManager = this.factory.Server.Host.Services.GetService(typeof(UserManager <User>))
                                             as UserManager <User>;

            var insertedUser = await userManager.FindByNameAsync(user.UserName);

            Assert.NotNull(insertedUser);
        }
        public async Task <IActionResult> LoginAsync([FromBody] UserCredentialsViewModel givenUser)
        {
            if (this.ModelState.IsValid == false)
            {
                return(this.BadRequest(this.ModelState));
            }

            var user = await this.tokenService.ValidateUser(givenUser.UserName, givenUser.Password);

            if (user == null)
            {
                this.logger.LogInformation("Invalid login attempt");

                return(this.BadRequest());
            }

            string refreshTokenString = this.tokenService.GenerateRefreshToken();
            string token = this.tokenService.GenerateJwtToken(user.UserName);

            RefreshToken refreshToken = new RefreshToken()
            {
                Token  = refreshTokenString,
                UserId = user.Id
            };

            await this.tokenService.SetRefreshToken(user, refreshToken);

            return(new OkObjectResult(new
            {
                user = user.ToViewModel(),
                token,
                refreshToken = refreshTokenString
            }));
        }
Example #5
0
        public async Task <IActionResult> EditMember(string id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            var applicationUser = await _context.ApplicationUsers.FindAsync(id);

            if (applicationUser == null)
            {
                return(NotFound());
            }

            var user = new UserCredentialsViewModel
            {
                Id       = applicationUser.Id,
                Name     = applicationUser.Name,
                Email    = applicationUser.Email,
                UserName = applicationUser.Email,
                Password = string.Empty
            };

            return(View(user));
        }
        public IActionResult login([FromBody] UserCredentialsViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            try
            {
                Players p = _context.Players.SingleOrDefault(m => m.Username == model.username);

                if (p == null)
                {
                    return(NotFound(p));
                }

                if (p.Password != model.password)
                {
                    return(new UnauthorizedResult());
                }

                return(Json(p));
            }
            catch (Exception ex)
            {
                return(new UnauthorizedResult());
            }
        }
Example #7
0
        public async Task LoginWithCorrectCredentialsShouldReturnToken()
        {
            // Arrange
            var user = new UserCredentialsViewModel()
            {
                Login    = _testUser.UserName,
                Password = TestPassword
            };

            // Act
            var result = await _manager.LoginUser(user);

            var savedUser = await _userManager.FindByNameAsync(user.Login);

            Assert.IsNotNull(result);
            Assert.IsInstanceOfType(result, typeof(AuthenticationResultViewModel));
            Assert.AreEqual(_testUser.UserName, result.Login);
            Assert.AreEqual(_testUser.FirstName, result.FirstName);
            Assert.AreEqual(_testUser.LastName, result.LastName);
            Assert.IsNotNull(savedUser);
            Assert.AreEqual(DateTime.UtcNow.Date, savedUser.LastLogin.Date);
            Assert.AreEqual(DateTime.UtcNow.Hour, savedUser.LastLogin.Hour);
            Assert.AreEqual(DateTime.UtcNow.Minute, savedUser.LastLogin.Minute);
            Assert.IsNotNull(result.Token);
        }
        private void LogonButtonClick(object sender, RoutedEventArgs e)
        {
            UserCredentials          creds = new UserCredentials();
            UserCredentialsViewModel vm    = new UserCredentialsViewModel(creds);
            LogonWindow win = new LogonWindow(vm);

            win.Show();
        }
Example #9
0
        public LoginControl()
        {
            InitializeComponent();
            LoggedUserContext.IncorrectCredentialsAttempt += OnIncorrectCredentialsAttempt;
            LoggedUserContext.UserLoggedIn += OnUserLoggedIn;
            UserCredentials creds = new UserCredentials();

            DataContext = new UserCredentialsViewModel(creds);
        }
        public IActionResult ForgotPassword()
        {
            var userResetPasswordModel = new UserCredentialsViewModel
            {
                SecurityAnswers = _securityQuestionBll.GetSecurityQuestions().Select(x => x.ToUserSecurityAnswerViewModel())
                                  .ToList()
            };

            return(View(userResetPasswordModel));
        }
Example #11
0
 public static UserCredentialsModel ToUserCredentialsModel(this UserCredentialsViewModel userCredentialsViewModel)
 {
     return(new UserCredentialsModel
     {
         Username = userCredentialsViewModel.Username,
         Password = userCredentialsViewModel.Password,
         SecurityAnswers = userCredentialsViewModel.SecurityAnswers.Select(x => x.ToUserSecurityAnswerModel())
                           .ToList()
     });
 }
        public IActionResult Register(UserCredentialsViewModel userCredentialsViewModel)
        {
            if (!ModelState.IsValid)
            {
                return(View(userCredentialsViewModel));
            }

            _userBll.CreateAccount(userCredentialsViewModel.ToUserCredentialsModel());

            return(RedirectToAction(Names.AccountsControllerLogin));
        }
Example #13
0
        public WelcomeScreenControl()
        {
            InitializeComponent();

            UserCredentials          creds = new UserCredentials();
            UserCredentialsViewModel vm    = new UserCredentialsViewModel(creds);

            LoginControl.DataContext = vm;
            LoginControl.UnsuccessfulLoginAttempt += OnUnsuccessfulLoginAttempt;
            LoginControl.UserAttemptingToLogin    += OnUserAttemptingToLogin;
        }
Example #14
0
        public async Task <IActionResult> CreateToken([FromBody] UserCredentialsViewModel credentials)
        {
            await HttpContext.Authentication.SignOutAsync(_externalCookieScheme);

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            try
            {
                var user = await _userManager.FindByEmailAsync(credentials.Email);

                if (user != null)
                {
                    bool isEmailConfirmed = user.EmailConfirmed == true;

                    if (isEmailConfirmed && _hasher.VerifyHashedPassword(user, user.PasswordHash, credentials.Password) == PasswordVerificationResult.Success)
                    {
                        var userClaims = await _userManager.GetClaimsAsync(user);

                        var claims = new[]
                        {
                            new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
                            new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                            new Claim(JwtRegisteredClaimNames.Email, user.Email)
                        }.Union(userClaims);

                        var key   = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Tokens:Key"]));
                        var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

                        var token = new JwtSecurityToken(
                            issuer: _config["Tokens:Issuer"],
                            audience: _config["Tokens:Audience"],
                            claims: claims,
                            expires: DateTime.UtcNow.AddMinutes(15),
                            signingCredentials: creds);

                        return(Ok(new
                        {
                            token = new JwtSecurityTokenHandler().WriteToken(token),
                            expiration = token.ValidTo
                        }));
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError($"Erro ao criar token:{ex}");
            }

            return(BadRequest());
        }
Example #15
0
        public async Task LoginWithNonExistingUserShouldThrowException()
        {
            // Arrange
            var user = new UserCredentialsViewModel()
            {
                Login    = "******",
                Password = "******"
            };

            // Act
            await _manager.LoginUser(user);
        }
Example #16
0
        public async Task LoginWithWrongPasswordShouldThrowException()
        {
            // Arrange
            var user = new UserCredentialsViewModel
            {
                Login    = _testUser.UserName,
                Password = TestPassword + "UNVALID"
            };

            // Act
            await _manager.LoginUser(user);
        }
Example #17
0
        public async Task LoginWithoutPasswordShouldThrowException()
        {
            // Arrange
            var credentials = new UserCredentialsViewModel
            {
                Login    = "******",
                Password = null
            };

            // Act
            await _manager.LoginUser(credentials);
        }
Example #18
0
        public async Task LoginWithoutLoginShouldThrowException()
        {
            // Arrange
            var credentials = new UserCredentialsViewModel()
            {
                Login    = null,
                Password = "******"
            };

            // Act
            await _manager.LoginUser(credentials);
        }
Example #19
0
        private void OkClicked(object sender, RoutedEventArgs e)
        {
            if (UserAttemptingToLogin != null)
            {
                UserAttemptingToLogin.Invoke(this, EventArgs.Empty);
            }
            UserCredentialsViewModel vm =
                DataContext as UserCredentialsViewModel;
            string login    = vm.Model.Username;
            string password = vm.Model.Password;

            LoggedUserContext.Logon(login, password);
        }
Example #20
0
        public async Task <IActionResult> Login([FromBody] UserCredentialsViewModel model)
        {
            if (model == null)
            {
                throw new UserActionException("Body", "Request body is invalid or empty", $"Model (Request body) is null when executing {nameof(Login)} method inside {nameof(AuthenticationController)}");
            }

            if (!ModelState.IsValid)
            {
                throw new UserActionException(ModelState.ToHashtable(), $"ModelState is not valid when executing {nameof(Login)} method inside {nameof(AuthenticationController)}");
            }

            return(Json(await _manager.LoginUser(model)));
        }
        public async Task LoginWithValidModelShouldHitLoginMethod()
        {
            // Arrange
            const string login     = "******";
            const string firstName = "Brecht";
            const string lastName  = "Carlier";
            const string token     = "UnitTestToken";

            var model = new UserCredentialsViewModel
            {
                Login    = login,
                Password = "******"
            };

            var manager = new Mock <IAuthenticationManager>();

            manager.Setup(m => m.LoginUser(model))
            .ReturnsAsync(new AuthenticationResultViewModel
            {
                LastName  = lastName,
                FirstName = firstName,
                Login     = model.Login,
                Token     = token
            });

            var controller = new AuthenticationController(manager.Object);


            // Act
            var result = await controller.Login(model);

            manager.Verify(m => m.LoginUser(model), Times.Exactly(1));

            // Assert
            Assert.IsNotNull(result);
            Assert.IsInstanceOfType(result, typeof(JsonResult));

            var jsonResult = (JsonResult)result;

            Assert.IsInstanceOfType(jsonResult.Value, typeof(AuthenticationResultViewModel));

            var jsonData = (AuthenticationResultViewModel)jsonResult.Value;

            Assert.AreEqual(login, jsonData.Login);
            Assert.AreEqual(lastName, jsonData.LastName);
            Assert.AreEqual(firstName, jsonData.FirstName);
            Assert.AreEqual(token, jsonData.Token);
        }
        public IActionResult Register()
        {
            if (User.Identity.IsAuthenticated)
            {
                return(RedirectToAction(Names.HomeControllerIndex, Names.Home));
            }

            var securityQuestions     = _securityQuestionBll.GetSecurityQuestions();
            var userRegisterViewModel = new UserCredentialsViewModel
            {
                SecurityAnswers = securityQuestions.Select(x => x.ToUserSecurityAnswerViewModel())
                                  .ToList()
            };

            return(View(userRegisterViewModel));
        }
        public IActionResult ForgotPassword(UserCredentialsViewModel userCredentialsViewModel)
        {
            if (!ModelState.IsValid)
            {
                return(View(userCredentialsViewModel));
            }

            var isResetSuccessfully = _userBll.ResetForgottenPassword(userCredentialsViewModel.ToUserCredentialsModel());

            if (isResetSuccessfully)
            {
                return(RedirectToAction(Names.AccountsControllerLogin));
            }

            ModelState.AddModelError(nameof(UserCredentialsViewModel.SecurityAnswers), ErrorMessages.SecurityAnsweredWrong);

            return(View(userCredentialsViewModel));
        }
Example #24
0
        public Result <UserCredentialsViewModel> GetCredetialsViewModel(string id)
        {
            SelectSpecification <AppUserEntity, UserCredentialsViewModel> userSpecification = new SelectSpecification <AppUserEntity, UserCredentialsViewModel>();

            userSpecification.AddFilter(x => x.Id == id);
            userSpecification.AddSelect(x => new UserCredentialsViewModel(
                                            x.Id,
                                            x.UserName));

            UserCredentialsViewModel userCredentials = _userRepository.SingleOrDefault(userSpecification);

            if (userCredentials == null)
            {
                return(Result.Fail <UserCredentialsViewModel>("no_user", "No user"));
            }

            return(Result.Ok(userCredentials));
        }
Example #25
0
        public async Task <IActionResult> EditMember(string id, UserCredentialsViewModel viewModel)
        {
            var emailDoesExits = _context.ApplicationUsers.Any(x => x.Email == viewModel.Email && x.Id != viewModel.Id);

            if (emailDoesExits)
            {
                ViewBag.Message = $"User name {viewModel.Email} is already taken.";
            }

            if (ModelState.IsValid && !emailDoesExits)
            {
                var editedUserNewValue = await _context.ApplicationUsers.FindAsync(id);

                editedUserNewValue.Name     = viewModel.Name;
                editedUserNewValue.Email    = viewModel.Email;
                editedUserNewValue.UserName = viewModel.Email;

                try
                {
                    if (!string.IsNullOrWhiteSpace(viewModel.Password))
                    {
                        var user = await _userManager.FindByIdAsync(id);

                        var token = await _userManager.GeneratePasswordResetTokenAsync(user);

                        await _userManager.ResetPasswordAsync(user, token, viewModel.Password);
                    }

                    await _userManager.UpdateAsync(editedUserNewValue);
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!_context.ApplicationUsers.Any(g => g.Id == viewModel.Id))
                    {
                        return(NotFound());
                    }
                    throw;
                }

                return(RedirectToAction("MemberList"));
            }
            return(View(viewModel));
        }
        public async Task <AuthenticationResultViewModel> LoginUser(UserCredentialsViewModel credentials)
        {
            #region Argument Checks
            if (credentials == null)
            {
                throw new ArgumentNullException(nameof(credentials), "Credentials cannot be null when generating an access token");
            }
            if (string.IsNullOrEmpty(credentials.Login))
            {
                throw new ArgumentNullException(nameof(credentials.Login), "Username cannot be null or empty to generate an access token");
            }
            if (string.IsNullOrEmpty(credentials.Password))
            {
                throw new ArgumentNullException(nameof(credentials.Login), "Password cannot be null or empty to generate an access token");
            }
            #endregion

            _logger.LogDebug($"Trying to sign in a user:{Environment.NewLine}Login: {credentials.Login}");
            var user = await _userManager.FindByNameAsync(credentials.Login);

            if (user == null)
            {
                throw new InvalidCredentialException($"User with {nameof(credentials.Login).ToLower()}: {credentials.Login} cannot be found!");
            }

            var identity = await GetIdentity(user, credentials.Password);

            var encodedJwt = await identity.GenerateJwtToken(_jwtOptions);

            // Update last login data
            user.LastLogin = DateTime.UtcNow;
            await _userManager.UpdateAsync(user);

            _logger.LogDebug($"User is succesfully authenticated:{Environment.NewLine}Login: {user.UserName}{Environment.NewLine}Firstname: {user.FirstName}{Environment.NewLine}Lastname: {user.LastName} ");
            return(new AuthenticationResultViewModel
            {
                FirstName = user.FirstName,
                LastName = user.LastName,
                Login = user.UserName,
                Token = encodedJwt
            });
        }
Example #27
0
        public async Task <IActionResult> ResetPassword(UserCredentialsViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var user = await _userManager.FindByEmailAsync(model.Email);

            if (user == null)
            {
                return(Ok(new { Message = "confirmação de Email." }));
            }

            var result = await _userManager.ResetPasswordAsync(user, model.Code, model.Password);

            if (result.Succeeded)
            {
                return(Ok(new { Message = "Senha resetada com sucesso." }));
            }

            AddErrors(result);
            return(BadRequest(ModelState));
        }
        public async Task <IActionResult> Post([FromBody] UserCredentialsViewModel userViewModel)
        {
            if (!this.ModelState.IsValid)
            {
                return(this.BadRequest(this.ModelState));
            }

            var user = new User()
            {
                UserName = userViewModel.UserName,
                Name     = userViewModel.Name
            };

            var result = await this.userManager.CreateAsync(user, userViewModel.Password);

            if (!result.Succeeded)
            {
                this.logger.LogDebug("Unable to create user", result.Errors.ToResponseString());

                return(new BadRequestObjectResult(result.Errors.ToResponseString()));
            }

            return(new OkResult());
        }
 public LoginWindow()
 {
     InitializeComponent();
     _userService = new UserService(_client);
     DataContext  = new UserCredentialsViewModel(_userService);
 }