예제 #1
0
        /// <summary>
        ///  Creates the external bank account for the customer.
        /// </summary>
        /// <param name="customerID">The corepro customer identifier.</param>
        /// <param name="institutionName">The bank name.</param>
        /// <param name="firstName">The first name.</param>
        /// <param name="lastName">The last name.</param>
        /// <param name="accountType">The external account type.</param>
        /// <param name="routingNumber">The routing number.</param>
        /// <param name="accountNumber">The account number.</param>
        /// <param name="isTrialDeposit">The is trial deposit.</param>
        /// <returns>The external account</returns>
        public ExternalAccount CreateExternalAccount(int customerID, string institutionName, string firstName, string lastName, string accountType, string routingNumber, string accountNumber, bool isTrialDeposit = false)
        {
            try
            {
                _connection = _connection ?? GetConnection();

                var externalAccountId = 0;
                if (!isTrialDeposit)
                {
                    //Creates the external account
                    externalAccountId = ExternalAccount.Create(customerID, institutionName, firstName, lastName, accountType,
                                                               routingNumber, accountNumber, string.Empty, string.Empty, _connection);
                }
                else
                {
                    //Creates the external account with micro deposit
                    externalAccountId = ExternalAccount.Initiate(customerID, institutionName, firstName, lastName, accountType,
                                                                 routingNumber, accountNumber, string.Empty, string.Empty, _connection);
                }

                //Gets the external account by external account identifier
                return(GetExternalAccount(customerID, externalAccountId));
            }
            catch (CoreProApiException ex)
            {
                var message = ex?.Errors?.FirstOrDefault()?.Message;
                throw new InvalidOperationException(message);
            }
        }
예제 #2
0
        public static async Task TestTransactionSigning()
        {
            using (var trezorManager = await TrezorFactory.GetWindowsConnectedLedgerManagerAsync(GetPin))
            {
                await trezorManager.InitializeAsync();

                var signer = new TrezorExternalSigner(trezorManager, 0);

                var account = new ExternalAccount(signer);
                await account.InitialiseAsync();

                account.InitialiseDefaultTransactionManager(new RpcClient(new Uri("http://localhost:8545")));
                var tx = new TransactionInput()
                {
                    Nonce    = new HexBigInteger(10),
                    GasPrice = new HexBigInteger(10),
                    Gas      = new HexBigInteger(21000),
                    To       = "0x689c56aef474df92d44a1b70850f808488f9769c",
                    Value    = new HexBigInteger(BigInteger.Parse("10000000000000000000")),
                    From     = "0x6A1D4583b83E5ef91EeA1E591aD333BD04853399"
                };
                var signature = await account.TransactionManager.SignTransactionAsync(tx);

                var accountNethereum = new Account("0x2e14c29aaecd1b7c681154d41f50c4bb8b6e4299a431960ed9e860e39cae6d29");
                accountNethereum.TransactionManager.Client = new RpcClient(new Uri("http://localhost:8545"));
                var signatureNethereum = await accountNethereum.TransactionManager.SignTransactionAsync(tx);

                System.Console.WriteLine("Trezor: " + signature);
                System.Console.WriteLine("Nethereum: " + signatureNethereum);
            }
        }
예제 #3
0
        protected async Task FillManager(SapPersonExcelRow contract, ExternalAccount externalAccount)
        {
            if (string.IsNullOrEmpty(contract.ManagerId))
            {
                _searchVm.Subordinate = contract;
                if (!string.IsNullOrEmpty(contract.AmRestManagerName))
                {
                    _searchVm.ManagerName = contract.AmRestManagerName;
                }

                var view = new SearchPeople()
                {
                    DataContext = _searchVm
                };
                var result = (bool)await DialogHost.Show(view, "ControlDialog");

                if (!result)
                {
                    throw new ArgumentNullException(nameof(contract.ManagerId), string.Format(Resources.PeopleUploadManagerNotSetMessage, contract.Name, contract.Surname));
                }
                externalAccount.ManagerId = _searchVm.SelectedUser.User.Id;
            }
            else
            {
                var manager = await _client.FindUserByIdentityNumber(contract.ManagerId);

                externalAccount.ManagerId = manager == null ? throw new ArgumentException(string.Format(Resources.PeopleUploadManagerNotFoundMessage, contract.Name, contract.Surname)) : manager.Id;
            }
        }
예제 #4
0
            private async Task CreateCustomerAccount(RegisterAdminCommand request, User user)
            {
                var customerStatus = await context.CustomerStatus.SingleOrDefaultAsync(o => o.Status.ToLower() == "active");

                if (customerStatus == null)
                {
                    throw new CustomerStatusNotFoundException();
                }

                var customer = new Customer
                {
                    UserId                = user.UserId,
                    CustomerStatusId      = customerStatus.CustomerStatusId,
                    Email                 = request.Dto.Email,
                    PhotoUrl              = request.Dto.PhotoUrl,
                    LastName              = request.Dto.LastName,
                    FirstName             = request.Dto.FirstName,
                    Address               = request.Dto.Address,
                    ContactNumber         = request.Dto.ContactNumber,
                    ActivateEmailReceipts = true
                };

                // create external account data
                var externalAccount = new ExternalAccount
                {
                    AccountId   = request.Dto.AccountId,
                    DateCreated = DateTime.UtcNow,
                    Type        = string.Empty,
                    UserId      = user.UserId
                };

                context.ExternalAccounts.Add(externalAccount);
                context.Customers.Add(customer);
                await context.SaveChangesAsync();
            }
예제 #5
0
        protected async Task <bool> ChangePassword(ExternalAccount account, IEnumerable <SapPersonExcelRow> inputRows)
        {
            var row = inputRows
                      .Where(_ => _.IdentityNumber == account.PersonLegalId &&
                             _.ContractNumber == account.ContractNumber &&
                             _.Status == ContractStatus.ACTIVE)
                      .SingleOrDefault(_defaultPasswordRequiredCondition);

            if (account.BackendType == AccountBackendType.ActiveDirectory || row == null)
            {
                return(false);
            }
            var existingUser = await _client.FindUserByIdentityNumber(account.PersonLegalId);

            bool result = false;

            try
            {
                result = await _client.ChangePasswordAsync(_defaultPassword, existingUser);
            }
            catch (ArgumentException ex)
            {
                if (!ex.Message.Contains("New password cannot be the same as old password."))
                {
                    throw;
                }
            }
            return(result);
        }
예제 #6
0
        public static async Task TestTransferTokenSigning()
        {
            using (var trezorManager = await TrezorFactory.GetWindowsConnectedLedgerManagerAsync(GetPin))
            {
                await trezorManager.InitializeAsync();

                var signer = new TrezorExternalSigner(trezorManager, 0);

                var account = new ExternalAccount(signer);
                await account.InitialiseAsync();

                var rpcClient = new RpcClient(new Uri("http://localhost:8545"));
                account.InitialiseDefaultTransactionManager(rpcClient);
                var web3 = new Web3.Web3(account, rpcClient);
                var tx   = new TransferFunction()
                {
                    Nonce       = 10,
                    GasPrice    = 10,
                    Gas         = 21000,
                    To          = "0x689c56aef474df92d44a1b70850f808488f9769c",
                    Value       = 100,
                    FromAddress = "0x6A1D4583b83E5ef91EeA1E591aD333BD04853399"
                };

                var signature = await web3.Eth.GetContractTransactionHandler <TransferFunction>().SignTransactionAsync("0x6810e776880c02933d47db1b9fc05908e5386b96", tx);

                var web32 = new Web3.Web3(new Account("0x2e14c29aaecd1b7c681154d41f50c4bb8b6e4299a431960ed9e860e39cae6d29"));
                var signatureNethereum = await web32.Eth.GetContractTransactionHandler <TransferFunction>()
                                         .SignTransactionAsync("0x6810e776880c02933d47db1b9fc05908e5386b96", tx);

                System.Console.WriteLine("Trezor: " + signature);
                System.Console.WriteLine("Nethereum: " + signatureNethereum);
            }
        }
예제 #7
0
        public ExternalAccount GetDetailUserByPartner(string accountNumber)
        {
            ExternalAccount res    = null;
            var             detail = _UserCollection.GetByAccountNumber(accountNumber);

            if (detail != null)
            {
                if (detail.Role == 1)
                {
                    res = new ExternalAccount();
                    res.AccountNumber = detail.AccountNumber;
                    res.Address       = detail.Address;
                    res.Email         = detail.Email;
                    if (detail.Gender == 0)
                    {
                        res.Gender = "Nam";
                    }
                    else if (detail.Gender == 1)
                    {
                        res.Gender = "Nữ";
                    }
                    else
                    {
                        res.Gender = "Khác";
                    }
                    res.Name  = detail.Name;
                    res.Phone = detail.Phone;
                }
            }

            return(res);
        }
예제 #8
0
        public async Task <IResult <ExternalAccount> > ExternalAccountSaveAsync(ExternalAccount inputDTO)
        {
            ProxyXFMAccount.ExternalAccountInput input = new ProxyXFMAccount.ExternalAccountInput();
            input.ExternalAccount = AutoMapper.Mapper.Map <ProxyXFMAccount.ExternalAccount>(inputDTO);
            input.InputContext    = this.UpdateContext <ProxyXFMAccount.Context>();
            var result = await InvokeMethodAsync <Domain.ExternalAccount, ProxyXFMAccount.WSAccountClient>("ExternalAccountSave", input);

            return(result);
        }
예제 #9
0
 protected override async Task RegisterUserToExternalEventAsync(ExternalAccount account, ExternalEvent externalEvent)
 {
     await _apiService.EnrollUserToCourseAsync(new TalentLmsEnrollmentDto
     {
         UserId   = account.ExternalAccountId,
         CourseId = externalEvent.ExternalEventId,
         Role     = TalentLmsEnrollmentDto.Learner // TODO: Instructor role support?
     });
 }
예제 #10
0
        private async Task <ExternalAccount> DangerouslyCreateExternalConnection(CreateConnection dto, Guid profileId)
        {
            var externalAccount = new ExternalAccount(dto.Provider, dto.Name, dto.ExternalId, profileId);

            await context.AddAsync(externalAccount);

            await authorizationService.AddPermission(profileId, AuthorizationHelper.GenerateARN(typeof(ExternalAccount), externalAccount.Id.ToString(), Shared.Permissions.ExternalAccount.Delete));

            return(externalAccount);
        }
        public virtual async Task <ExternalEventSyncResult> RunSynchronizationAsync(ExternalAccount account, Registration registration)
        {
            if (account == null)
            {
                throw new ArgumentException(nameof(account));
            }

            if (registration == null)
            {
                throw new ArgumentException(nameof(registration));
            }

            if (registration.EventInfo == null)
            {
                throw new ArgumentException(nameof(registration));
            }

            var externalEvent = await EnsureExternalEventAsync(registration.EventInfo);

            if (externalEvent == null)
            {
                return(ExternalEventSyncResult.NotSynced);
            }

            if (await _context.ExternalRegistrations
                .AnyAsync(e => e.ExternalEventId == externalEvent.LocalId &&
                          e.ExternalAccountId == account.LocalId))
            {
                return(ExternalEventSyncResult.AlreadySynced);
            }

            await RegisterUserToExternalEventAsync(account, externalEvent);

            var externalRegistration = new ExternalRegistration
            {
                ExternalEvent   = externalEvent,
                ExternalAccount = account,
                Registration    = registration
            };

            try
            {
                await _context.ExternalRegistrations.AddAsync(externalRegistration);

                await _context.SaveChangesAsync();
            }
            catch (DbUpdateException e) when(e.IsUniqueKeyViolation())
            {
                _logger.LogWarning(e, e.Message);
                _context.ExternalRegistrations.Remove(externalRegistration);
                return(ExternalEventSyncResult.AlreadySynced);
            }

            return(ExternalEventSyncResult.Synced);
        }
예제 #12
0
        /// <summary>
        /// Insert an External Account for a User
        /// </summary>
        /// <param name="userID">ID of User</param>
        /// <param name="username">Registration account username</param>
        /// <param name="serviceID">ID of registration account service</param>
        /// <returns>The external account or null if errors occur</returns>
        public ExternalAccount addExternalAccount(int userID, string username, int serviceID)
        {
            ExternalAccount ea = new ExternalAccount()
            {
                userID    = userID,
                username  = username,
                serviceID = serviceID
            };

            return(AddEntity(ea));
        }
예제 #13
0
 /// <summary>
 /// Disconnects the external account for corepro
 /// </summary>
 /// <param name="customerId">The corepro customer identifier.</param>
 /// <param name="externalAccountId">The external account identifier.</param>
 /// <returns></returns>
 public bool ArchiveExternalAccount(int customerId, int externalAccountId)
 {
     try
     {
         _connection = _connection ?? GetConnection();
         return(ExternalAccount.Archive(customerId, externalAccountId, _connection));
     }
     catch (CoreProApiException ex)
     {
         var message = ex?.Errors?.FirstOrDefault()?.Message;
         throw new InvalidOperationException(message);
     }
 }
예제 #14
0
        private decimal ProcessExternalAccount(ExternalAccount externalAccount, IDatafeedAPI datafeedApi, Account account, out decimal availableBalance)
        {
            string encryptedAccessKey = _datafeedDataService.GetAccessKeyForExternalAccount(externalAccount.Provider, externalAccount.VendorID, Task.ClientID);

            availableBalance = 0;

            if (string.IsNullOrEmpty(externalAccount?.AccountID) || string.IsNullOrEmpty(encryptedAccessKey) || datafeedApi == null)
            {
                return(0);
            }

            List <Transaction> transactions = datafeedApi.GetAccountTransactions(externalAccount.AccountID, encryptedAccessKey, out decimal accountBalance, out availableBalance);

            Log($"Fetched [{transactions.Count}] transactions from provider");

            List <Transaction> sortedTransactions = new List <Transaction>();

            foreach (var transaction in transactions)
            {
                transaction.ClientID    = Task.ClientID;
                transaction.AccountID   = account.ID;
                transaction.AccountName = account?.AccountName ?? "Unknown";
                if (sortedTransactions.Where(t => t.ID == transaction.ID).Count() == 0)
                {
                    sortedTransactions.Add(transaction);
                }
            }

            //Run Algorithms
            sortedTransactions = MerchantAlgorithm(sortedTransactions);
            sortedTransactions = VendorAlgorithm(sortedTransactions);

            // Remove any pending transactions that have now been settled (Pending transaction not supplied by provider anymore indicates that  it has settled under a different transaction id)
            var exitingPendingTransactions = _transactionDataService.GetTransactions(account.ClientID).Where(t => t.Status == Status.PENDING && t.Owner != "User");

            foreach (var transaction in exitingPendingTransactions)
            {
                if (!sortedTransactions.Where(t => t.Status == Status.PENDING).Any(t => t.ID == transaction.ID))
                {
                    _transactionDataService.DeleteTransaction(transaction.ID, transaction.ClientID);
                }
            }

            //Add All sorted transactions
            foreach (Transaction transaction in sortedTransactions)
            {
                bool?imported = _transactionDataService.ImportDatafeedTransaction(transaction);
            }

            return(accountBalance);
        }
예제 #15
0
        public Task <ExternalAccount> WriteExternalAccountAsync(
            ExternalAccount externalAccount)
        {
            var userAccountId = externalAccount.UserAccount != null ?
                                externalAccount.UserAccount.Id : externalAccount.UserAccountId;
            var userAccountEntity = _context.UserAccounts
                                    .SingleOrDefault(x => x.Id == userAccountId);

            if (userAccountEntity == null)
            {
                _logger.LogError(
                    "{existingUserAccountId} not found in database",

                    userAccountId);
                return(null);
            }

            var externalAccountEntity = _context.ExternalAccounts
                                        .SingleOrDefault(x =>
                                                         x.Provider == externalAccount.Provider &&
                                                         x.Subject == externalAccount.Subject);

            if (externalAccountEntity == null)
            {
                _logger.LogDebug("{0} {1} not found in database",
                                 externalAccount.Provider, externalAccount.Subject);

                externalAccountEntity = externalAccount.ToEntity();
                _context.ExternalAccounts.Add(externalAccountEntity);
            }
            else
            {
                _logger.LogDebug("{0} {1} found in database",
                                 externalAccountEntity.Provider,
                                 externalAccountEntity.Subject);

                externalAccount.UpdateEntity(externalAccountEntity);
            }

            try
            {
                _context.SaveChanges();
                return(Task.FromResult(externalAccountEntity.ToModel()));
            }
            catch (Exception ex)
            {
                _logger.LogError(0, ex, "Exception storing external account");
            }

            return(Task.FromResult <ExternalAccount>(null));
        }
예제 #16
0
            private async Task <bool> CreateCustomerAccount(RegisterUser request, User user, string verificationCode)
            {
                var customerStatus = await context.CustomerStatus.SingleOrDefaultAsync(o => o.Status.ToLower() == "active");

                if (customerStatus == null)
                {
                    throw new CustomerStatusNotFoundException();
                }

                var customer = new Customer
                {
                    UserId                = user.UserId,
                    CustomerStatusId      = customerStatus.CustomerStatusId,
                    Email                 = request.Dto.Email,
                    PhotoUrl              = request.Dto.PhotoUrl,
                    LastName              = request.Dto.LastName,
                    FirstName             = request.Dto.FirstName,
                    Address               = request.Dto.Address,
                    ContactNumber         = request.Dto.ContactNumber,
                    ActivateEmailReceipts = true,
                    IsVerified            = false,
                    VerificationCode      = verificationCode
                };

                var role = await context.Roles.SingleOrDefaultAsync(o => o.RoleName.ToLower() == "customer");

                var userRole = new UserInRole
                {
                    UserId = user.UserId,
                    RoleId = role.RoleId
                };

                // create external account data
                var externalAccount = new ExternalAccount
                {
                    AccountId   = request.Dto.AccountId,
                    DateCreated = DateTime.UtcNow,
                    Type        = string.Empty,
                    UserId      = user.UserId
                };

                context.UserInRoles.Add(userRole);
                context.ExternalAccounts.Add(externalAccount);
                context.Customers.Add(customer);
                if (await context.SaveChangesAsync() > 0)
                {
                    return(true);
                }

                return(false);
            }
예제 #17
0
        public async Task AddPossibleUsernameAsync(int personId, int externalAccountId, string username, CancellationToken cancellationToken = default)
        {
            var externalAccountSuggestion = new ExternalAccount
            {
                PersonId                  = personId,
                ExternalPlatformId        = externalAccountId,
                ExternalAccountIdentifier = username,
                IsSuggestionAccepted      = ExternalAccountSuggestionStatus.Pending,
            };

            _dbContext.ExternalAccounts.Add(externalAccountSuggestion);

            await _dbContext.SaveChangesAsync(cancellationToken);
        }
예제 #18
0
        /// <summary>
        /// Verifies an external account.
        /// </summary>
        /// <param name="customerID">The corepro customer identifier.</param>
        /// <param name="externalAccountId">The external account identifier.</param>
        /// <param name="firstAmount">The first amount.</param>
        /// <param name="secondAmount">The second amount.</param>
        /// <returns><c>True</c>, If verified. Otherwise, <c>False</c>.</returns>
        public bool VerifyExternalAccount(int customerID, int externalAccountId, decimal firstAmount, decimal secondAmount)
        {
            try
            {
                _connection = _connection ?? GetConnection();

                return(ExternalAccount.Verify(customerID, externalAccountId, firstAmount, secondAmount, _connection));
            }
            catch (CoreProApiException ex)
            {
                var message = ex?.Errors?.FirstOrDefault()?.Message;
                throw new InvalidOperationException(message);
            }
        }
예제 #19
0
        public async Task UpdateLastUsedExternalAccountAsync(ExternalAccount externalAccount)
        {
            // TODO: user time service
            var now = DateTime.UtcNow;

            externalAccount.LastLoginAt = now;
            externalAccount.UpdatedAt   = now;

            await _userAccountStore.WriteExternalAccountAsync(externalAccount);

            // Emit event
            await _eventService.RaiseSuccessfulUserAccountUpdatedEventAsync(
                externalAccount.UserAccountId);
        }
        public EthereumOracleConnector(string endpoint, string contractAddress, string pkcsUser, string key)
        {
            this.contractAddress = contractAddress;
            var client = new Nethereum.JsonRpc.Client.RpcClient(new Uri(endpoint));

            account = new ExternalAccount("0x7957Db97cB19fB029968595E9325e2E5C92EAF33", new HSMExternalEthSigner(pkcsUser, key), 1);
            account.NonceService = new InMemoryNonceService("0x7957Db97cB19fB029968595E9325e2E5C92EAF33", client);
            account.InitialiseDefaultTransactionManager(client);

            web3     = new Web3Geth(account, endpoint);
            contract = web3.Eth.GetContract(abi, contractAddress);

            tokenDictionary.Add("USDT", "0xdac17f958d2ee523a2206206994597c13d831ec7");
            tokenDictionary.Add("MTL", "0xF433089366899D83a9f26A773D59ec7eCF30355e");
            tokenDictionary.Add("USDC", "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48");
            tokenDictionary.Add("BAT", "0x0d8775f648430679a709e98d2b0cb6250d2887ef");
            tokenDictionary.Add("CRO", "0xa0b73e1ff0b80914ab6fe0444e65848c4c34450b");
            tokenDictionary.Add("DEX", "0x497bAEF294c11a5f0f5Bea3f2AdB3073DB448B56");
            tokenDictionary.Add("TUSD", "0x0000000000085d4780B73119b644AE5ecd22b376");
            tokenDictionary.Add("DAI", "0x89d24a6b4ccb1b6faa2625fe562bdd9a23260359");
            tokenDictionary.Add("EGT", "0x8e1b448ec7adfc7fa35fc2e885678bd323176e34");
            tokenDictionary.Add("ENJ", "0xf629cbd94d3791c9250152bd8dfbdf380e2a3b9c");
            tokenDictionary.Add("HT", "0x6f259637dcd74c767781e37bc6133cd6a68aa161");
            tokenDictionary.Add("INB", "0x17aa18a4b64a55abed7fa543f2ba4e91f2dce482");
            tokenDictionary.Add("KCS", "0x039b5649a59967e3e936d7471f9c3700100ee1ab");
            tokenDictionary.Add("ELF", "0xbf2179859fc6D5BEE9Bf9158632Dc51678a4100e");

            tokenDictionary.Add("ZRX", "0xe41d2489571d322189246dafa5ebde1f4699f498");
            tokenDictionary.Add("LINK", "0x514910771af9ca656af840dff83e8264ecf986ca");
            tokenDictionary.Add("MANA", "0x0f5d2fb29fb7d3cfee444a200298f468908cc942");
            tokenDictionary.Add("MATIC", "0x7D1AfA7B718fb893dB30A3aBc0Cfc608AaCfeBB0");
            tokenDictionary.Add("MCO", "0xb63b606ac810a52cca15e44bb630fd42d8d1d83d");
            tokenDictionary.Add("MKR", "0x9f8f72aa9304c8b593d555f12ef6589cc3a579a2");
            tokenDictionary.Add("ZB", "0xbd0793332e9fb844a52a205a233ef27a5b34b927");
            tokenDictionary.Add("OMG", "0xd26114cd6EE289AccF82350c8d8487fedB8A0C07");
            tokenDictionary.Add("PAX", "0x8e870d67f660d95d5be530380d0ec0bd388289e1");
            tokenDictionary.Add("PERL", "0xb5a73f5fc8bbdbce59bfd01ca8d35062e0dad801");
            tokenDictionary.Add("LAMB", "0x8971f9fd7196e5cee2c1032b50f656855af7dd26");
            tokenDictionary.Add("SEELE", "0xb1eef147028e9f480dbc5ccaa3277d417d1b85f0");
            tokenDictionary.Add("REP", "0x1985365e9f78359a9B6AD760e32412f4a445E862");
            tokenDictionary.Add("REALT", "0x46cc7ec70746f4cbd56ce5fa9bb7d648398eaa5c");
            tokenDictionary.Add("BRZ", "0x420412e765bfa6d85aaac94b4f7b708c89be2e2b");
            tokenDictionary.Add("SNT", "0x744d70fdbe2ba4cf95131626614a1763df805b9e");
            tokenDictionary.Add("NXPS", "0xa15c7ebe1f07caf6bff097d8a589fb8ac49ae5b3");
            tokenDictionary.Add("GUSD", "0x056fd409e1d7a124bd7017459dfea2f387b6d5cd");
            tokenDictionary.Add("BNB", "0xB8c77482e45F1F44dE1745F52C74426C631bDD52");
        }
    static void Main(string[] args)
    {
        var account = new ExternalAccount()
        {
            Name = "Someone"
        };
        string json = JsonConvert.SerializeObject(account);
        string base64EncodedExternalAccount = Convert.ToBase64String(Encoding.UTF8.GetBytes(json));

        byte[] byteArray = Convert.FromBase64String(base64EncodedExternalAccount);

        string jsonBack    = Encoding.UTF8.GetString(byteArray);
        var    accountBack = JsonConvert.DeserializeObject <ExternalAccount>(jsonBack);

        Console.WriteLine(accountBack.Name);
        Console.ReadLine();
    }
예제 #22
0
        protected async Task FillPosition(SapPersonExcelRow contract, ExternalAccount externalAccount)
        {
            var positions = await _client.GetPositionsAsync();

            var existingPosition = positions
                                   .FirstOrDefault(_ => string.Equals(_.Name, contract.Position, StringComparison.OrdinalIgnoreCase));

            if (existingPosition == null)
            {
                externalAccount.PositionName = contract.Position;
            }
            else
            {
                externalAccount.PositionName = existingPosition.Name;
                externalAccount.PositionId   = existingPosition.Id;
            }
        }
예제 #23
0
        public async Task <IActionResult> RegisterExternal([FromBody] RegisterExternalBindingModel model)
        {
            EnsureDatabaseCreated(_applicationDbContext);
            if (ModelState.IsValid)
            {
                var isValid = await _externalAuthManager.VerifyExternalAccessToken(model.AccessToken, model.Provider);

                if (!isValid)
                {
                    return(BadRequest(new OpenIdConnectResponse
                    {
                        Error = OpenIdConnectConstants.Errors.InvalidRequest,
                        ErrorDescription = "Invalid access_token, this usually happens when it is expired"
                    }));
                }

                var profile = await _externalAuthManager.GetProfile(model.AccessToken, model.Provider);

                var user = new ApplicationUser {
                    UserName  = profile.email,
                    Email     = profile.email,
                    FirstName = profile.first_name,
                    LastName  = profile.last_name
                };
                var externalAccount = new ExternalAccount()
                {
                    Id             = Guid.NewGuid().ToString(),
                    AddedAt        = DateTimeOffset.Now,
                    Provider       = model.Provider,
                    ProviderUserId = profile.id
                };
                user.ExternalAccounts.Add(externalAccount);

                var result = await _userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    return(Ok());
                }
                AddErrors(result);
            }

            // If we got this far, something failed.
            return(BadRequest(ModelState));
        }
예제 #24
0
        public static ExternalAccount AddExternalAccount(ref ExternalAccount externalAccount, out string error)
        {
            error = "";
            KoloAndroidEntities context = new KoloAndroidEntities();

            try
            {
                context.ExternalAccounts.Add(externalAccount);
                context.SaveChanges();
                context.Dispose();
                return(externalAccount);
            }
            catch (Exception ex)
            {
                error = ExceptionHelper.GetExceptionMessage(ex);
            }
            return(null);
        }
예제 #25
0
        public static bool RemoveExternalAccount(ExternalAccount externalAccount, out string error)
        {
            error = "";
            KoloAndroidEntities context = new KoloAndroidEntities();

            try
            {
                var tmp = context.ExternalAccounts.Remove(externalAccount);
                context.SaveChanges();
                context.Dispose();
                return(true);
            }
            catch (Exception ex)
            {
                error = ExceptionHelper.GetExceptionMessage(ex);
            }
            return(false);
        }
예제 #26
0
        public void LoadByExternalProviderAsync_WhenUserAccountExists_ExpectUserAccountRetured(
            DbContextOptions <UserAccountDbContext> options)
        {
            var testExternalAccount = new ExternalAccount
            {
                Email    = "*****@*****.**",
                Provider = "yahoo",
                Subject  = "123456789"
            };

            var testUserAccount = new UserAccount
            {
                Id       = Guid.NewGuid(),
                Email    = "*****@*****.**",
                Accounts = new List <ExternalAccount>
                {
                    testExternalAccount
                }
            };

            using (var context =
                       new UserAccountDbContext(options, StoreOptions))
            {
                context.UserAccounts.Add(testUserAccount.ToEntity());
                context.SaveChanges();
            }

            UserAccount userAccount;

            using (var context =
                       new UserAccountDbContext(options, StoreOptions))
            {
                var store = new UserAccountStore(
                    context,
                    NullLogger <UserAccountStore> .Create()
                    );

                userAccount = store.LoadByExternalProviderAsync(
                    testExternalAccount.Provider,
                    testExternalAccount.Subject).Result;
            }

            Assert.NotNull(userAccount);
        }
예제 #27
0
        public static ExternalAccount UpdateExternalAccount(ExternalAccount externalAccount, out string error)
        {
            error = "";
            KoloAndroidEntities context = new KoloAndroidEntities();

            try
            {
                ExternalAccount tmp = context.ExternalAccounts.FirstOrDefault(e => e.IdExternalAccount == externalAccount.IdExternalAccount);
                tmp = externalAccount;
                context.SaveChanges();
                context.Dispose();
                return(tmp);
            }
            catch (Exception ex)
            {
                error = ExceptionHelper.GetExceptionMessage(ex);
            }
            return(null);
        }
예제 #28
0
        /// <summary>
        /// Checks whether the user is authenticated with a new or used service.
        /// </summary>
        private void manageMultipleAccount(Security.User user)
        {
            UserID = user.UserId;
            List <Storage.Service> services = sto.getServicesByUserID(UserID);

            if (services == null)
            {
                showError("An error occurred during recovery services", false);
            }

            bool addExt = true;

            foreach (Storage.Service serv in services)
            {
                if (serv.serviceID == servID)
                {
                    addExt = false;
                    break;
                }
            }
            if (addExt)
            {
                /*
                 * Controllo che non esista un altro user (diverso da quello corrente) che abbia questo account esterno.
                 * Se esiste devo fondere i due utenti perche' rappresentano la stessa persona.
                 */
                Storage.User userAlredyExist = sto.getUserByExternalAccount(servID, LoginUserName);
                if (userAlredyExist != null)
                {
                    showError("External account already exists. UserId=" + userAlredyExist.userID, false);
                }

                // Operazione da eseguire su db ora solo se gia' registrato
                if (user.Registered)
                {
                    ExternalAccount extAcc = sto.addExternalAccount(UserID, LoginUserName, servID);
                    if (extAcc == null)
                    {
                        showError("An error occurred during the addition of new service", false);
                    }
                }
            }
        }
예제 #29
0
        protected async Task <ExternalAccountResponse> UploadAccount(ExternalAccount externalAccount)
        {
            var contractResult = new ExternalAccountResponse();
            var existingUser   = await _client.FindUserByIdentityNumber(externalAccount.PersonLegalId);

            if (existingUser == null)
            {
                contractResult = await _client.CreateExternalAccount(externalAccount);
            }
            else
            {
                var existingContract = existingUser.Contracts.Find(_ => _.ContractNumber == externalAccount.ContractNumber);
                contractResult = existingContract == null ?
                                 await _client.CreateExternalAccount(externalAccount) :
                                 await _client.UpdateExternalAccount(existingContract.Id, externalAccount);
            }
            var passwordChanged = await ChangePassword(externalAccount, InputRows);

            return(contractResult);
        }
예제 #30
0
        public async Task <AuthResponse> Authorize(ExternalAccount userAccount)
        {
            var payload = new Dictionary <string, string>
            {
                { "username", userAccount.username },
                { "password", userAccount.password },
                { "client_id", "c82SH0WZOsabOXGP2sxqcj34FxkvfnWRZBKlBjFS" },
                { "device_token", "71bf6292-064c-4967-898c-04c1f93176f4" },
                { "grant_type", "password" }
            };

            var authorizedUser = await AuthorizeUser(payload);

            if (authorizedUser.access_token == null && authorizedUser.mfa_required == false)
            {
                throw new Exception("Authorization failed");
            }

            return(authorizedUser);
        }