public async Task <IApplicationResult> LoginAsync(UserCredentialDto userCredential) { return(await ExecuteAsync(async() => { if (userCredential == null) { return new ApplicationResult <LoginResultDto> { Status = ApplicationResultStatus.Unauthenticated, Data = new LoginResultDto { Status = LoginStatus.InvalidEmailOrPassword } } } ; var byEmail = _userPredicateFactory.CreateByEmail(userCredential.Email); var user = await _unitOfWork.Users.GetFirstAsync(byEmail); if (user == null) { return new ApplicationResult <LoginResultDto> { Status = ApplicationResultStatus.Unauthenticated, Data = new LoginResultDto { Status = LoginStatus.InvalidEmailOrPassword } } } ; if (!user.EmailConfirmed) { return new OkApplicationResult <LoginResultDto> { Data = new LoginResultDto { Status = LoginStatus.UnconfirmedEmail } } } ; if (!user.Active) { return new OkApplicationResult <LoginResultDto> { Data = new LoginResultDto { Status = LoginStatus.Inactive } } } ; if (user.IsLocked()) { user.GenerateDefaultPassword(); user.ResetAccessFailedCount(); await _unitOfWork.Users.UpdateAsync(user); var email = await _emailFactory.CreateForUserForgotPasswordAsync(user); _emailService.SendAsync(email); return new OkApplicationResult <LoginResultDto> { Data = new LoginResultDto { Status = LoginStatus.Locked } }; } //TODO use encrypted password if (!user.HasPassword(userCredential.Password)) { user.AccessFailedCount++; await _unitOfWork.Users.UpdateAsync(user); return new OkApplicationResult <LoginResultDto> { Data = new LoginResultDto { Status = LoginStatus.InvalidEmailOrPassword } }; } user.LastLoginTime = DateTime.UtcNow; user.ResetAccessFailedCount(); await _unitOfWork.Users.UpdateAsync(user); var tokenGenerateResponse = await _tokenService.GenerateAsync(new TokenGenerateRequest { Expires = _appSettingsService.DefaultTokenExpiresTime, Claims = new List <Claim> { new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()), new Claim(ClaimTypes.Email, user.Email), new Claim(ClaimTypes.GivenName, user.FirstName), new Claim(ClaimTypes.Surname, user.GetSurname()) } }); if (tokenGenerateResponse == null) { throw new InternalServerException("SecurityToken could not be generated"); } return new OkApplicationResult <LoginResultDto> { Data = new LoginResultDto { Status = user.IsUsingCustomPassword ? LoginStatus.Success : LoginStatus.NonCustomPassword, SecurityToken = new SecurityTokenDto { Token = tokenGenerateResponse.SecurityToken, Expires = tokenGenerateResponse.Expires } } }; }, false)); }