public override AccountsResponse GetAccounts(string bank_id, string view_id)
        {
            AccountsResponse result = new AccountsResponse();

            try {
                LoginBindResponse loginData = doLogin();
                ///banks/322/accounts/owner
                string urlData = String.Format("banks/{0}/accounts/{1}", bank_id, view_id);

                string JsonResult = new FluentClient(config.Url)
                                    .GetAsync(urlData)
                                    .WithHeader("Authorization", "JWT " + loginData.token)
                                    .WithOptions(true)
                                    .AsString().Result;

                try {
                    result.accounts = JsonConvert.DeserializeObject <List <Account> >(JsonResult);
                } catch (Exception) { }

                result.executeStatus = getExecuteStatus(JsonResult, urlData);
            } catch (CustomException cEx) {
                result.executeStatus = cEx.convertToCustomStatus();
            } catch (Exception ex) {
                result.executeStatus = new CustomException(ExceptionsCodes.UnexpectedException, "", ex.Message).convertToCustomStatus();
            }
            return(result);
        }
        public async Task <ServiceLink> CreateLink(string userId, IQuestradeLink questradeLink)
        {
            QuestradeCredentials questradeCredentials = await GetLinkCredentials(questradeLink);

            QuestradeClient  client   = m_clientFactory.CreateClient(questradeCredentials);
            AccountsResponse response = await client.FetchAccounts();

            ServiceType serviceType = ServiceType.Questrade;
            string      serviceId   = response.UserId.ToString();

            if (LinkExists(userId, serviceType, serviceId))
            {
                throw new ConflictException();
            }
            ServiceLink link = new ServiceLink(userId, ServiceType.Questrade, serviceId, questradeLink.IsPractice);

            using (IDbContextTransaction transaction = m_context.Database.BeginTransaction())
            {
                m_context.ServiceLinks.Add(link);
                m_context.SaveChanges();

                Credentials credentials = new Credentials(link, questradeCredentials);
                m_context.Credentials.Add(credentials);
                m_context.SaveChanges();

                m_accountsManager.SynchronizeAccounts(link, response.Accounts);

                transaction.Commit();
            }
            return(link);
        }
Example #3
0
        private async Task <List <Account> > GetAccounts(Configuration configuration)
        {
            AccountsApi      accountsApi = new AccountsApi(configuration);
            AccountsResponse accounts    = await accountsApi.GetAccountsAsync("default");

            return(accounts.Accounts.Where(a => a.Closed == false).ToList());
        }
Example #4
0
        public override AccountsResponse GetAccounts(string bank_id = "", string view_id = "")
        {
            AccountsResponse result = new AccountsResponse();

            try {
                ValoresLoginResponse loginData = doLogin();

                string urlData = "accounts/getOwnAccounts";

                var request = (HttpWebRequest)WebRequest.Create(config.Url + urlData);
                request.ContentType = "application/json";
                request.Method      = "POST";

                if (cookieContainer != null)
                {
                    request.CookieContainer = cookieContainer;
                }
                else
                {
                    request.CookieContainer = new CookieContainer();
                }

                using (var streamWriter = new StreamWriter(request.GetRequestStream())) {
                    streamWriter.Write("{}");
                }

                var httpResponse = (HttpWebResponse)request.GetResponse();

                ValoresAccountsResponse response = new ValoresAccountsResponse();

                string JsonResult = "";
                using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) {
                    JsonResult = streamReader.ReadToEnd();
                    response   = JsonConvert.DeserializeObject <ValoresAccountsResponse>(JsonResult);
                }

                if (response.message != null)
                {
                    result.executeStatus = new CustomStatus(ExceptionsCodes.ApiException, response.message.message, response.message.code, "accounts/getMovementsDetail");
                    return(result);
                }

                result = response.convertToStandar();
                result.executeStatus = new CustomStatus();

                return(result);
            } catch (CustomException cEx) {
                result.executeStatus = cEx.convertToCustomStatus();
            } catch (Exception ex) {
                result.executeStatus = new CustomException(ExceptionsCodes.UnexpectedException, "", ex.Message).convertToCustomStatus();
            }

            return(result);
        }
        public async Task <IEnumerable <Account> > SynchronizeAccounts(string userId, int linkId)
        {
            ServiceLink link = m_context.ServiceLinks.Find(linkId, userId);

            if (link == null)
            {
                return(null);
            }
            QuestradeClient  client   = m_clientFactory.CreateClient(userId, linkId);
            AccountsResponse response = await client.FetchAccounts();

            return(SynchronizeAccounts(link, response.Accounts));
        }
        public static IActionResult GetAccountsSummary(
            [HttpTrigger(AuthorizationLevel.Function, "get", Route = "accounts")] HttpRequest req,
            [CosmosDB(
                 databaseName: "Rodrap50",
                 collectionName: "Financials",
                 ConnectionStringSetting = "CosmosDBConnection",
                 Id = "1000",
                 PartitionKey = "accountsummary")] AccountsResponse accounts,
            ILogger log)
        {
            log.LogInformation("C# HTTP GetAccounts trigger function processed a request.");

            return(new OkObjectResult(accounts));
        }
        public AccountsResponse Get()
        {
            AccountsResponse accounts;

            try
            {
                accounts = new AccountsResponse(_db.GetAll());
            }
            catch (Exception e)
            {
                _logger.LogError(e.StackTrace);
                throw;
            }
            return(accounts);
        }
        public async Task InvokeWithNullBudgetAccountsReturnsNull()
        {
            // Arrange
            var appSettings = new AppSettings
            {
                Splitwise = new Splitwise
                {
                    ConsumerKey            = "consumerKey",
                    ConsumerSecret         = "consumerSecret",
                    FriendEmail            = "friendEmail",
                    TransactionsDatedAfter = new DateTimeOffset()
                },
                Ynab = new Ynab
                {
                    PersonalAccessToken  = "personalAccessToken",
                    BudgetName           = "budgetName",
                    SplitwiseAccountName = "splitwiseAccountName"
                }
            };

            var ynabBudgetGuid = Guid.NewGuid();
            var ynabBudgets    = new BudgetSummaryResponse
            {
                Data = new BudgetModel
                {
                    Budgets = new List <BudgetSummary> {
                        new() { Name = "budgetName", Id = ynabBudgetGuid }
                    }
                }
            };

            _ynabClient.GetBudgets(true).Returns(ynabBudgets);

            var ynabBudgetAccounts = new AccountsResponse();

            _ynabClient.GetBudgetAccounts(ynabBudgetGuid).Returns(ynabBudgetAccounts);

            // Act
            _sut = new GetYnabInfoOperation(_logger, _ynabClient);
            var result = await _sut.Invoke(appSettings);

            // Assert
            Assert.Null(result);
        }
Example #9
0
        public override AccountsResponse GetAccount(string AccountId, string bank_id, string view_id)
        {
            AccountsResponse result = new AccountsResponse();

            result = GetAccounts();

            if (result.accounts != null)
            {
                Account account = new Account();
                account = result.accounts.FirstOrDefault(a => a.id == AccountId);

                result.accounts.Clear();
                result.accounts.Add(account);

                result.executeStatus = new CustomStatus();
            }

            return(result);
        }
Example #10
0
        // GET: SetBids/Create
        public ActionResult Create(int id)
        {
            ViewBag.ProductsId = new SelectList(db.Products.Where(o => o.Id == id), "Id", "ItemName", id);
            ViewBag.Product    = db.Products.Where(o => o.Id == id).FirstOrDefault();
            var results = GetAccounts.Get();
            List <AccountsResponse> accountid = new List <AccountsResponse>();
            var ktima = GetCurrentInfo.Get();

            ViewBag.ktimaInfo  = ktima;
            ViewBag.selectedid = id;
            foreach (var item in results)
            {
                AccountsResponse accid = new AccountsResponse();
                accid.AccountId = item.AccountId;
                accountid.Add(accid);
            }

            ViewBag.AccountNo = new SelectList(accountid, "AccountId", "AccountId");
            return(View());
        }
Example #11
0
        // Загрузить портфели
        static async Task LoadTinkoff()
        {
            //  брокерские счета
            TinkoffAccounts = await GetAsync <AccountsResponse>(token, "https://api-invest.tinkoff.ru/openapi/user/accounts");

            TinkoffPaperAccounts    = new Dictionary <string, PortfolioList>();
            TinkoffCurrencyAccounts = new Dictionary <string, CurrencyList>();

            if ((TinkoffAccounts != null) && (TinkoffAccounts.status == "Ok") && (TinkoffAccounts.payload != null) && (TinkoffAccounts.payload.accounts != null))
            {
                foreach (var item in TinkoffAccounts.payload.accounts)
                {
                    // портфели счетов
                    var Portfolio = await GetAsync <PortfolioResponse>(token, $"https://api-invest.tinkoff.ru/openapi/portfolio?brokerAccountId={item.brokerAccountId}");

                    if ((Portfolio != null) && (Portfolio.status == "Ok") && (Portfolio.payload != null))
                    {
                        Portfolio.payload.account = new UserAccount()
                        {
                            brokerAccountId = item.brokerAccountId, brokerAccountType = item.brokerAccountType
                        };
                        TinkoffPaperAccounts.Add(item.brokerAccountId, Portfolio.payload);
                    }

                    // портфели валют
                    var Currency = await GetAsync <CurrencyResponse>(token, $"https://api-invest.tinkoff.ru/openapi/portfolio/currencies?brokerAccountId={item.brokerAccountId}");

                    if ((Currency != null) && (Currency.status == "Ok") && (Currency.payload != null) && (Currency.payload.currencies != null))
                    {
                        bool _finish = false;

                        do
                        {
                            _finish = true;

                            foreach (var item1 in Currency.payload.currencies)
                            {
                                if (item1.currency != "USD")
                                {
                                    if (item1.currency != "EUR")
                                    {
                                        if (item1.currency != "RUB")
                                        {
                                            Currency.payload.currencies.Remove(item1);
                                            _finish = false;
                                            break;
                                        }
                                    }
                                }
                            }
                        } while (!_finish);
                    }

                    if ((Currency != null) && (Currency.status == "Ok") && (Currency.payload != null))
                    {
                        Currency.payload.account = new UserAccount()
                        {
                            brokerAccountId = item.brokerAccountId, brokerAccountType = item.brokerAccountType
                        };
                        TinkoffCurrencyAccounts.Add(item.brokerAccountId, Currency.payload);
                    }
                }
            }
        }
Example #12
0
        /// <summary>
        /// Calls the Enzoic CheckCredentials API in a secure fashion to check whether the provided username and password
        /// are known to be compromised.
        /// This call is made securely to the server - only a salted and hashed representation of the credentials are passed and
        /// the salt value is not passed along with it.
        /// @see <a href="https://www.enzoic.com/docs/credentials-api">https://www.enzoic.com/docs/credentials-api</a>
        /// </summary>
        /// <param name="username">the username to check - may be an email address or username</param>
        /// <param name="password">the password to check</param>
        /// <param name="lastCheckDate">(Optional) The timestamp for the last check you performed for this user.  If the date/time you provide
        /// for the last check is greater than the timestamp Enzoic has for the last breach affecting this user, the check will
        /// not be performed.This can be used to substantially increase performance.Can be set to null if no last check was performed
        /// or the credentials have changed since.</param>
        /// <param name="excludeHashTypes">(Optional) An array of PasswordTypes to ignore when calculating hashes for the credentials check.
        /// By excluding computationally expensive PasswordTypes, such as BCrypt, it is possible to balance the performance of this
        /// call against security.Can be set to null if you don't wish to exclude any hash types.</param>
        /// <returns>true if the credentials are known to be compromised, false otherwise</returns>
        public bool CheckCredentials(string username, string password, DateTime?lastCheckDate = null,
                                     PasswordType[] excludeHashTypes = null)
        {
            String response = MakeRestCall(
                apiBaseURL + ACCOUNTS_API_PATH + "?username="******"GET", null);

            if (response == "404")
            {
                // this is all we needed to check for this - email wasn't even in the DB
                return(false);
            }

            // deserialize response
            AccountsResponse accountsResponse = JsonConvert.DeserializeObject <AccountsResponse>(response);

            // see if the lastCheckDate was later than the lastBreachDate - if so bail out
            if (lastCheckDate.HasValue && lastCheckDate.Value >= accountsResponse.lastBreachDate)
            {
                return(false);
            }

            int bcryptCount = 0;

            List <string> credentialHashes = new List <string>();
            StringBuilder queryString      = new StringBuilder();

            foreach (PasswordHashSpecification hashSpec in accountsResponse.PasswordHashesRequired)
            {
                if (excludeHashTypes != null && excludeHashTypes.Contains(hashSpec.HashType))
                {
                    // this type is excluded
                    continue;
                }

                // bcrypt gets far too expensive for good response time if there are many of them to calculate.
                // some mostly garbage accounts have accumulated a number of them in our DB and if we happen to hit one it
                // kills performance, so short circuit out after at most 2 BCrypt hashes
                if (hashSpec.HashType != PasswordType.BCrypt || bcryptCount <= 2)
                {
                    if (hashSpec.HashType == PasswordType.BCrypt)
                    {
                        bcryptCount++;
                    }

                    String credentialHash = CalcCredentialHash(username, password, accountsResponse.Salt, hashSpec);

                    if (credentialHash != null)
                    {
                        credentialHashes.Add(credentialHash);
                        if (queryString.Length == 0)
                        {
                            queryString.Append("?partialHashes=").Append(credentialHash.Substring(0, 10));
                        }
                        else
                        {
                            queryString.Append("&partialHashes=").Append(credentialHash.Substring(0, 10));
                        }
                    }
                }
            }

            if (queryString.Length > 0)
            {
                String credsResponse = MakeRestCall(
                    apiBaseURL + CREDENTIALS_API_PATH + queryString, "GET", null);

                if (credsResponse != "404")
                {
                    // loop through candidate hashes returned and see if we have a match with the exact hash
                    dynamic responseObj = JObject.Parse(credsResponse);

                    foreach (dynamic candidate in responseObj.candidateHashes)
                    {
                        if (credentialHashes.FirstOrDefault(hash => hash == candidate.ToString()) != null)
                        {
                            return(true);
                        }
                    }
                }
            }

            return(false);
        }
 public Accounts(AccountsResponse accountsResponse)
 {
     Spends  = (decimal)accountsResponse.Spends / 100;
     Cash    = (decimal)accountsResponse.Cash / 100;
     Savings = (decimal)accountsResponse.Savings / 100;
 }
Example #14
0
        public void AccountsResponse()
        {
            var accountsResponse = new AccountsResponse(_jToken);

            Assert.AreEqual(2, accountsResponse.Data.Accounts.Count);
        }
Example #15
0
 AccountsResponse Map(IEnumerable <Account> accounts)
 => AccountsResponse.Create(_mapper.Map <IEnumerable <AccountDto> >(accounts));