public async Task <Results <RefreshTokenContract> > Login(PandaUserLoginContract account) { var refreshTokenIsNullOrEmpty = await _userLogic.RefreshTokenIsNullOrEmpty(account.Email); if (!refreshTokenIsNullOrEmpty) { return(PandaResponse.CreateErrorResponse <RefreshTokenContract>("User still loged in.")); } var signInResult = await _userLogic.Login(account); if (signInResult.IsError()) { return(PandaResponse.CreateErrorResponse <RefreshTokenContract>(signInResult.Errors.ToArray())); } account.Id = signInResult.Data.Id; var token = _jwtTokenService.GenerateToken(account.Email, account.Id.ToString()); var refreshToken = _jwtTokenService.GenerateRefreshToken(); var tokenData = new RefreshTokenContract { RefreshToken = refreshToken, Token = token }; var refreshTokenResult = await _userLogic.UpdateRefreshTokenToUser(account.Email, refreshToken); if (refreshTokenResult.IsError()) { return(PandaResponse.CreateErrorResponse <RefreshTokenContract>(refreshTokenResult.Errors.ToArray())); } return(PandaResponse.CreateSuccessResponse(tokenData)); }
public async Task <Results <bool> > RunStatement(PandaStatementCreateContract statement) { if (string.IsNullOrEmpty(statement.PandaAccountId)) { return(PandaResponse.CreateErrorResponse <bool>("Account id not found")); } statement.CreatedAt = statement.CreatedAt == null ? DateTime.Now : statement.CreatedAt; var newStatement = new PandaStatement(); _mapper.Map(statement, newStatement); Results <bool> runStateMentResult = await _accountRepository.CreateStatement(newStatement); if (runStateMentResult.IsError()) { return(runStateMentResult); } if (string.IsNullOrEmpty(newStatement.PandaAccountId)) { return(PandaResponse.CreateErrorResponse <bool>("Panda account Id Invalid")); } Results <bool> balanceIsUpdated = await _accountRepository.UpdateAccountBalance(newStatement.PandaAccountId, newStatement.Balances); if (balanceIsUpdated.IsError()) { return(balanceIsUpdated); } return(PandaResponse.CreateSuccessResponse(true)); }
public async Task <Results <bool> > Logout(long IdentityUser) { var logOutResult = await _userLogic.Logout(IdentityUser); if (!logOutResult) { return(PandaResponse.CreateErrorResponse <bool>("Can not log out.")); } return(PandaResponse.CreateSuccessResponse(logOutResult)); }
public async Task RefreshTokenUserTestSuccess() { #region Mock Success TestRefreshSuccess.prarameter.Token = jwtService.GenerateToken(TestRefreshSuccess.user.Email, TestRefreshSuccess.user.Id.ToString()); TestRefreshSuccess.prarameter.RefreshToken = jwtService.GenerateRefreshToken(); var claimPrincipa = jwtService.GetPrincipalFromExpiredToken(TestRefreshSuccess.prarameter.Token); _jwtServiceMocking.Setup(s => s.GetPrincipalFromExpiredToken(TestRefreshSuccess.prarameter.Token)) .Returns(claimPrincipa); var emailFromClaim = jwtService.GetValueFromClaimType(claimPrincipa, JwtRegisteredClaimNames.Email); _jwtServiceMocking.Setup(s => s.GetValueFromClaimType(claimPrincipa, JwtRegisteredClaimNames.Email)) .Returns(emailFromClaim); var userIdFromClaim = jwtService.GetValueFromClaimType(claimPrincipa, JwtRegisteredClaimNames.NameId); _jwtServiceMocking.Setup(s => s.GetValueFromClaimType(claimPrincipa, JwtRegisteredClaimNames.NameId)) .Returns(userIdFromClaim); TestRefreshSuccess.response.Token = jwtService.GenerateToken(claimPrincipa.Claims.ToList()); TestRefreshSuccess.response.RefreshToken = jwtService.GenerateRefreshToken(); _jwtServiceMocking.Setup(s => s.GenerateToken(emailFromClaim, userIdFromClaim)) .Returns(TestRefreshSuccess.response.Token); _jwtServiceMocking.Setup(s => s.GenerateRefreshToken()) .Returns(TestRefreshSuccess.response.RefreshToken); _userLogicMocking.Setup(s => s.ValidateRefreshToken(TestRefreshSuccess.user.Email, TestRefreshSuccess.prarameter.RefreshToken)) .Returns(Task.FromResult(PandaResponse.CreateSuccessResponse(true))); _userLogicMocking.Setup(s => s.UpdateRefreshTokenToUser(TestRefreshSuccess.user.Email, TestRefreshSuccess.response.RefreshToken)) .Returns(Task.FromResult(PandaResponse.CreateSuccessResponse(true))); userFacade = new UserFacade(_jwtServiceMocking.Object, _userLogicMocking.Object); #endregion var result = await userFacade.RefreshToken(TestRefreshSuccess.prarameter); _jwtServiceMocking.Verify(v => v.GetPrincipalFromExpiredToken(TestRefreshSuccess.prarameter.Token)); _jwtServiceMocking.Verify(v => v.GetValueFromClaimType(claimPrincipa, JwtRegisteredClaimNames.NameId)); _jwtServiceMocking.Verify(v => v.GenerateToken(emailFromClaim, userIdFromClaim)); _jwtServiceMocking.Verify(v => v.GenerateRefreshToken()); _userLogicMocking.Verify(v => v.ValidateRefreshToken(TestRefreshSuccess.user.Email, TestRefreshSuccess.prarameter.RefreshToken)); _userLogicMocking.Verify(v => v.UpdateRefreshTokenToUser(TestRefreshSuccess.user.Email, TestRefreshSuccess.response.RefreshToken)); Assert.Equal(TestRefreshSuccess.response.RefreshToken, result.Data.RefreshToken); Assert.Equal(TestRefreshSuccess.response.Token, result.Data.Token); }
public CanLoginOnlyOneDeviceTest() { mock = new MockRepository(MockBehavior.Default); _configMocking = mock.Create <IConfiguration>(); _configMocking.SetupGet(x => x[It.Is <string>(s => s == "JWT:Key")]) .Returns("PandaBank AuthenticationKey For JWT Token"); _configMocking.SetupGet(x => x[It.Is <string>(s => s == "JWT:ExpiredAt")]) .Returns("30"); _configMocking.SetupGet(x => x[It.Is <string>(s => s == "JWT:Issuer")]) .Returns("PandaBankIssuer"); _configMocking.SetupGet(x => x[It.Is <string>(s => s == "JWT:Audience")]) .Returns("PandaBankAudience"); var pandaSecureKey = "pandaSecureKey"; _configMocking.SetupGet(x => x[It.Is <string>(s => s == "SecureKey:Self")]) .Returns(pandaSecureKey); jwtService = new JwtTokenService(_configMocking.Object); _userLogicMocking = new Mock <IUserLogic>(); #region Success _userLogicMocking.Setup(s => s.Logout(1)) .Returns(Task.FromResult(true)); _userLogicMocking.Setup(s => s.RefreshTokenIsNullOrEmpty(TestDataPandaLoginOneDeviceSuccess.pandaUser.Email)) .Returns(Task.FromResult(true)); _userLogicMocking.Setup(s => s.Login(TestDataPandaLoginOneDeviceSuccess.pandaUser)) .Returns(Task.FromResult(PandaResponse.CreateSuccessResponse(TestDataPandaLoginOneDeviceSuccess.CreateUserSuccessPandaUser(now)))); _userLogicMocking.Setup(s => s.UpdateRefreshTokenToUser(TestDataPandaLoginOneDeviceSuccess.pandaUser.Email, It.IsAny <string>())) .Returns(Task.FromResult(PandaResponse.CreateSuccessResponse(true))); #endregion #region Fail _userLogicMocking.Setup(s => s.Logout(0)) .Returns(Task.FromResult(false)); #endregion userFacade = new UserFacade( jwtService, _userLogicMocking.Object); }
public async Task <Results <bool> > ValidateRefreshToken( string email, string refreshToken ) { string savedRefreshToken = await _userRepository.GetRefreshToken(email); if (refreshToken != savedRefreshToken) { return(PandaResponse.CreateErrorResponse <bool>("Refresh token Invalid")); } return(PandaResponse.CreateSuccessResponse(true)); }
public async Task <Results <PandaUserContract> > GetMyAccount(long IdentityUser) { var pandaUser = await _userManager.FindByIdAsync(IdentityUser.ToString()); var newPanda = new PandaUserContract(); _mapper.Map(pandaUser, newPanda); if (newPanda != null && pandaUser != null) { return(PandaResponse.CreateSuccessResponse(newPanda)); } return(PandaResponse.CreateErrorResponse <PandaUserContract>("User not exist")); }
public async Task <Results <RefreshTokenContract> > RefreshToken(RefreshTokenContract token) { var principal = _jwtTokenService.GetPrincipalFromExpiredToken(token.Token); if (principal == null) { return(PandaResponse.CreateErrorResponse <RefreshTokenContract>("Invalid refresh token")); } var email = _jwtTokenService.GetValueFromClaimType(principal, JwtRegisteredClaimNames.Email); if (string.IsNullOrEmpty(email)) { return(PandaResponse.CreateErrorResponse <RefreshTokenContract>("Invalid claim email")); } var userId = _jwtTokenService.GetValueFromClaimType(principal, JwtRegisteredClaimNames.NameId); if (string.IsNullOrEmpty(userId)) { return(PandaResponse.CreateErrorResponse <RefreshTokenContract>("Invalid claim userId")); } var tokenValid = await _userLogic.ValidateRefreshToken(email, token.RefreshToken); if (tokenValid.IsError()) { return(PandaResponse.CreateErrorResponse <RefreshTokenContract>(tokenValid.Errors.ToArray())); } var newJwtToken = _jwtTokenService.GenerateToken(email, userId); var newRefreshToken = _jwtTokenService.GenerateRefreshToken(); var updateRefreshTokenResult = await _userLogic.UpdateRefreshTokenToUser(email, newRefreshToken); if (updateRefreshTokenResult.IsError()) { return(PandaResponse.CreateErrorResponse <RefreshTokenContract>(updateRefreshTokenResult.Errors.ToArray())); } var result = PandaResponse.CreateSuccessResponse <RefreshTokenContract>( new RefreshTokenContract { Token = newJwtToken, RefreshToken = newRefreshToken }); return(result); }
public async Task <Results <bool> > DeleteAccount(long identityUser, string accountId) { Results <bool> unActiveResult = await _accountLogic.UnActiveAccount(identityUser, accountId); if (unActiveResult.IsError()) { return(unActiveResult); } bool canActive = await _accountLogic.CanActiveAccount(identityUser, accountId); if (canActive != false) { return(PandaResponse.CreateErrorResponse <bool>("Something wrong with account")); } return(PandaResponse.CreateSuccessResponse(canActive)); }
public async Task <Results <bool> > UpdateRefreshToken(string email, string refreshToken) { var pandaUser = await _repo.GetQueryAble <PandaUser>() .Where(w => w.Email.ToLower().Equals(email.ToLower())) .FirstOrDefaultAsync(); if (pandaUser != null) { pandaUser.RefreshToken = refreshToken; await _repo.SaveAsync(); return(PandaResponse.CreateSuccessResponse <bool>(true)); } return(PandaResponse.CreateErrorResponse <bool>("Error when refresh token")); }
public async Task <Results <bool> > SaveAsync() { try { var result = await _msGenericDb.SaveChangesAsync(); return(PandaResponse.CreateSuccessResponse(result > 0)); } catch (Exception ex) { var tran = _msGenericDb.Database.CurrentTransaction; if (tran != null) { tran.Rollback(); } return(PandaResponse.CreateErrorResponse <bool>(ex.Message, ex)); } }
public async Task <Results <PandaUser> > Login(PandaUserLoginContract account) { var signInResult = await _signInManager.PasswordSignInAsync(account.Email, account.Password, false, false); if (signInResult.Succeeded) { return(PandaResponse.CreateSuccessResponse(await _userManager.FindByEmailAsync(account.Email))); } else { bool emailValid = await _userRepository.EmailValid(account.Email); if (!emailValid) { return(PandaResponse.CreateErrorResponse <PandaUser>("Email inValid.")); } return(PandaResponse.CreateErrorResponse <PandaUser>("Password inValid.")); } }
public ValidateModelWhenCallApiTest(WebApplicationFactory <Startup> factory) { _factory = factory; var mock = new MockRepository(MockBehavior.Default); userFacadeMocking = mock.Create <IUserFacade>(); userFacadeMocking.Setup(set => set.CreateUser(It.IsAny <PandaUserContract>())) .Returns(Task.FromResult(PandaResponse.CreateSuccessResponse((long)1))); void ConfigureTestServices(IServiceCollection services) { services.AddSingleton <IValidator <PandaUserContract>, CreatePandaUserValidator>(); services.AddSingleton <IUserFacade>(userFacadeMocking.Object); }; client = _factory .WithWebHostBuilder(builder => builder.ConfigureTestServices(ConfigureTestServices)) .CreateClient(); }
public async Task <Results <bool> > UpdateStatement(long identityUser, PandaStatementCreateContract statement, Enums.PandaStatementStatus status) { statement.Status = status; bool canActive = await _accountLogic.CanActiveAccount(identityUser, statement.PandaAccountId); if (!canActive) { return(PandaResponse.CreateErrorResponse <bool>("Account suspended")); } bool canUpdateBalance = await _accountLogic.CanUpdateBalance(statement.PandaAccountId, statement.Balances, status); if (canUpdateBalance == false) { return(PandaResponse.CreateErrorResponse <bool>("Can not update balance")); } var runStatementResult = await _accountLogic.RunStatement(statement); return(runStatementResult); }
public async Task <Results <long> > CreateUser(PandaUserContract account) { var emailValid = PandaValidator.EmailIsValid(account.Email); if (!emailValid) { return(PandaResponse.CreateErrorResponse <long>("Email Invalid")); } var user = await _userManager.FindByEmailAsync(account.Email); if (user != null) { return(PandaResponse.CreateSuccessResponse(user.Id)); } var newAccount = new PandaUser { Email = account.Email, FirstName = account.FirstName, LastName = account.LastName, UserName = account.Email, CreatedAt = now, UpdatedAt = now, }; var result = await _userManager.CreateAsync(newAccount, account.Password); if (result.Succeeded) { return(PandaResponse.CreateSuccessResponse(newAccount.Id)); } else { return(PandaResponse.CreateErrorResponse <long>(result.Errors.Select(s => s.Code + " : " + s.Description).ToArray())); } }
public async Task <Results <bool> > CreateAccount(long identityUser, PandaAccountCreateContract account) { account.Balances = 0; account.Active = true; account.UserAccounts = new List <UserAccountCreateContract> { new UserAccountCreateContract { PandaUserId = identityUser } }; account.Id = await _accountLogic.GenerateAccountId(); if (string.IsNullOrEmpty(account.Id)) { return(PandaResponse.CreateErrorResponse <bool>("Error while generate account id")); } Results <bool> createAccountResult = await _accountLogic.CreateAccount(account); if (string.IsNullOrEmpty(account.Id)) { createAccountResult.Errors.Insert(0, "Error while create account"); return(createAccountResult); } //_accountLogic.AddPaticipant account.PandaStatement.FirstOrDefault().PandaAccountId = account.Id; var depositInitResult = await UpdateStatement(identityUser, account.PandaStatement.FirstOrDefault(), Enums.PandaStatementStatus.Deposit); if (depositInitResult.IsError()) { depositInitResult.Errors.Insert(0, "Error while deposit money"); return(depositInitResult); } return(PandaResponse.CreateSuccessResponse(true)); }
public async Task <Results <List <TbDest> > > GetPagingAsync <TbSource, TbDest>( Expression <Func <TbSource, bool> > predicate, Expression <Func <TbSource, TbDest> > selector, PagingParameters paging, bool?tracking = null, bool?lazyLoading = null) where TbDest : class where TbSource : class { if (lazyLoading == false) { _msGenericDb.ChangeTracker.LazyLoadingEnabled = false; } var query = _msGenericDb.Set <TbSource>().Where(predicate).Select(selector); var results = await QueryExt.PagingResultProjectionAsync <IQueryable <TbDest>, TbDest>(query, paging); if (results.IsError()) { var err = PandaResponse.CreateErrorResponse <List <TbDest> >(""); err.Errors = results.Errors.ToList(); return(err); } List <TbDest> result; if (tracking == false) { result = await results.Data?.AsNoTracking().ToListAsync(); } else { result = await results.Data?.ToListAsync(); } var response = PandaResponse.CreateSuccessResponse(result, results.PageInfo); return(response); }
public virtual async Task <Results <TResult> > ExecuteWithTransactionAsync <TResult>(Func <Task <TResult> > func) { using (var t = _msGenericDb.Database.BeginTransaction()) { try { var result = await func.Invoke(); t.Commit(); return(new Results <TResult>() { Data = result }); } catch (Exception e) { if (t != null) { t.Rollback(); } return(PandaResponse.CreateErrorResponse <TResult>(GetAllMessages(e))); } } }
public AccountFacadeTest() { var mock = new MockRepository(MockBehavior.Default); _accountLogicMocking = new Mock <IAccountLogic>(); #region CreateAccount _accountLogicMocking .Setup(s => s.GenerateAccountId()) .Returns(Task.FromResult(accountIdSuccess)); var testDataPass = PandaAccountCreateContractTestData.pandaAccountCreateContracts[indexPass]; var testDataFail = PandaAccountCreateContractTestData.pandaAccountCreateContracts[indexFail]; _accountLogicMocking .Setup(s => s.CreateAccount(testDataPass)) .Returns(Task.FromResult(PandaResponse.CreateSuccessResponse(true))); _accountLogicMocking .Setup(s => s.CreateAccount(testDataFail)) .Returns(Task.FromResult(PandaResponse.CreateErrorResponse <bool>("test"))); #endregion #region DeleteAccount _accountLogicMocking .Setup(s => s.UnActiveAccount(userIdSuccess, accountIdSuccess)) .Returns(Task.FromResult(PandaResponse.CreateSuccessResponse(true))); _accountLogicMocking .Setup(s => s.UnActiveAccount(userIdSuccess, accountIdFail)) .Returns(Task.FromResult(PandaResponse.CreateSuccessResponse(true))); _accountLogicMocking .Setup(s => s.UnActiveAccount(userIdFail, accountIdSuccess)) .Returns(Task.FromResult(PandaResponse.CreateSuccessResponse(true))); _accountLogicMocking .Setup(s => s.UnActiveAccount(userIdFail, accountIdFail)) .Returns(Task.FromResult(PandaResponse.CreateSuccessResponse(true))); #endregion #region UpdateStatement _accountLogicMocking .Setup(s => s.CanActiveAccount(userIdSuccess, accountIdSuccess)) .Returns(Task.FromResult(true)); _accountLogicMocking .Setup(s => s.CanActiveAccount(userIdSuccess, accountIdFail)) .Returns(Task.FromResult(false)); _accountLogicMocking .Setup(s => s.CanActiveAccount(userIdFail, accountIdSuccess)) .Returns(Task.FromResult(false)); _accountLogicMocking .Setup(s => s.CanActiveAccount(userIdFail, accountIdFail)) .Returns(Task.FromResult(false)); _accountLogicMocking .Setup(s => s.CanUpdateBalance(testDataPass.PandaStatement[0].PandaAccountId, testDataPass.PandaStatement[0].Balances, It.IsAny <Enums.PandaStatementStatus>())) .Returns(Task.FromResult(true)); _accountLogicMocking .Setup(s => s.CanUpdateBalance(testDataPass.PandaStatement[0].PandaAccountId, testDataFail.PandaStatement[0].Balances, It.IsAny <Enums.PandaStatementStatus>())) .Returns(Task.FromResult(false)); _accountLogicMocking .Setup(s => s.CanUpdateBalance(testDataFail.PandaStatement[0].PandaAccountId, testDataPass.PandaStatement[0].Balances, It.IsAny <Enums.PandaStatementStatus>())) .Returns(Task.FromResult(false)); _accountLogicMocking .Setup(s => s.CanUpdateBalance(testDataFail.PandaStatement[0].PandaAccountId, testDataFail.PandaStatement[0].Balances, It.IsAny <Enums.PandaStatementStatus>())) .Returns(Task.FromResult(false)); _accountLogicMocking .Setup(s => s.RunStatement(testDataPass.PandaStatement[0])) .Returns(Task.FromResult(PandaResponse.CreateSuccessResponse(true))); _accountLogicMocking .Setup(s => s.RunStatement(testDataFail.PandaStatement[0])) .Returns(Task.FromResult(PandaResponse.CreateErrorResponse <bool>("test"))); #endregion accountFacade = new AccountFacade( _accountLogicMocking.Object); }
public AccountLogicTest() { var mock = new MockRepository(MockBehavior.Default); _accountRepository = new Mock <IAccountRepository>(); var mappingConfig = new MapperConfiguration(mc => { mc.AddProfile(new MappingProfile()); }); _mapper = mappingConfig.CreateMapper(); #region CanActiveAccount _accountRepository .Setup(s => s.GetAccountStatus(AccountIdSuccess)) .Returns(Task.FromResult(true)); _accountRepository .Setup(s => s.GetAccountStatus(AccountIdFail)) .Returns(Task.FromResult(false)); _accountRepository .Setup(s => s.IsPaticipant(AccountIdSuccess, UserIdSuccess)) .Returns(Task.FromResult(true)); _accountRepository .Setup(s => s.IsPaticipant(AccountIdSuccess, userIdFail)) .Returns(Task.FromResult(false)); _accountRepository .Setup(s => s.IsPaticipant(AccountIdFail, UserIdSuccess)) .Returns(Task.FromResult(false)); _accountRepository .Setup(s => s.IsPaticipant(AccountIdFail, userIdFail)) .Returns(Task.FromResult(false)); #endregion #region CanUpdateBalance _accountRepository .Setup(s => s.GetAccountBalance(accountHundred)) .Returns(Task.FromResult(balanceHundred)); _accountRepository .Setup(s => s.GetAccountBalance(accountThousand)) .Returns(Task.FromResult(balanceThousand)); #endregion #region RunStatement var test0 = PandaStatementCreateContractTestData.pandaStatementCreateContracts(now)[0]; var new0 = new PandaStatement(); _mapper.Map(test0, new0); var test1 = PandaStatementCreateContractTestData.pandaStatementCreateContracts(now)[1]; var new1 = new PandaStatement(); _mapper.Map(test1, new1); _accountRepository .Setup(s => s.CreateStatement(It.Is <PandaStatement>(m => m.Balances == new0.Balances && m.CreatedAt == new0.CreatedAt && m.Id == new0.Id && m.Status == new0.Status ))) .Returns(Task.FromResult(PandaResponse.CreateSuccessResponse(true))); _accountRepository .Setup(s => s.UpdateAccountBalance(new0.PandaAccountId, new0.Balances)) .Returns(Task.FromResult(PandaResponse.CreateSuccessResponse(true))); _accountRepository .Setup(s => s.CreateStatement(new1)) .Returns(Task.FromResult(PandaResponse.CreateErrorResponse <bool>("test error"))); _accountRepository .Setup(s => s.UpdateAccountBalance(new1.PandaAccountId, new1.Balances)) .Returns(Task.FromResult(PandaResponse.CreateErrorResponse <bool>("test error"))); #endregion accountLogic = new AccountLogic( _accountRepository.Object, _mapper); }