예제 #1
0
        public ScenarioSession ResumeScenario(string userSubject, int id)
        {
            _logger.Info($"{nameof(ResumeScenario)}({userSubject}, {id})");
            try
            {
                ScenarioSession scenarioSession = _dataAccessService.GetScenarioSessions(userSubject).FirstOrDefault(s => s.ScenarioId == id);

                if (scenarioSession == null)
                {
                    throw new ScenarioSessionNotFoundException(userSubject, id);
                }

                bool needInitialize = false;
                if (!_activeScenarios.TryGetValue(userSubject, out ScenarioMonitoringData scenarioMonitoringData))
                {
                    needInitialize = true;
                }
                else if (scenarioMonitoringData.ScenarioId != id)
                {
                    needInitialize = true;
                }

                if (needInitialize)
                {
                    scenarioMonitoringData = new ScenarioMonitoringData
                    {
                        ScenarioId        = id,
                        ScenarioSessionId = scenarioSession.ScenarioSessionId,
                        ActivationTime    = scenarioSession.StartTime,
                        LastUseTime       = DateTime.UtcNow
                    };
                    _activeScenarios.AddOrUpdate(userSubject, scenarioMonitoringData, (k, v) => v);


                    ScenarioDefinition scenarioDefinition = _scenarios[id];
                    IEnumerable <Client.DataLayer.Model.Scenarios.ScenarioAccount> scenarioAccounts = _dataAccessService.GetScenarioAccounts(scenarioSession.ScenarioSessionId);

                    foreach (var scenarioAccount in scenarioAccounts)
                    {
                        AccountDescriptor account = _accountsService.GetById(scenarioAccount.AccountId);
                        if (account.AccountType == AccountType.IdentityProvider || account.AccountType == AccountType.ServiceProvider)
                        {
                            AccountDescriptor accountDescriptor = _accountsService.Authenticate(scenarioAccount.AccountId, "qqq");
                            _executionContextManager.InitializeStateExecutionServices(accountDescriptor.AccountId, accountDescriptor.SecretSpendKey);
                        }
                    }
                }
                else
                {
                    scenarioMonitoringData.LastUseTime = DateTime.UtcNow;
                }

                return(scenarioSession);
            }
            catch (Exception ex)
            {
                _logger.Error($"Failed {nameof(ResumeScenario)}({userSubject}, {id})", ex);
                throw;
            }
        }
예제 #2
0
        public async Task<IActionResult> Get()
        {
            string token = this.Request.Headers["Authorization"].ToString().Substring("Bearer ".Length);
            
            _AccountService.Authenticate(token);

            var accounts = await _AccountService.GetAsync();

            return Ok(accounts);
        }
예제 #3
0
        public void Initialize(CancellationToken cancellationToken)
        {
            _logger.Info($"Initializing {nameof(O10InherenceService)}");

            InherenceSetting inherenceSetting = _dataAccessService.GetInherenceSetting(Name);

            if (inherenceSetting == null)
            {
                inherenceSetting = CreateO10Inherence();
            }

            AccountId = inherenceSetting.AccountId;
            _logger.LogIfDebug(() => $"[{AccountId}]: {nameof(Initialize)} proceeding");


            AccountDescriptor accountDescriptor = _accountsService.GetById(inherenceSetting.AccountId);

            if (accountDescriptor == null)
            {
                _dataAccessService.RemoveInherenceSetting(Name);
                inherenceSetting  = CreateO10Inherence();
                accountDescriptor = _accountsService.Authenticate(inherenceSetting.AccountId, GetDefaultO10InherencePassword());
                if (accountDescriptor == null)
                {
                    throw new Exception($"{nameof(O10InherenceService)} initialization failed");
                }
            }
            else
            {
                accountDescriptor = _accountsService.Authenticate(inherenceSetting.AccountId, GetDefaultO10InherencePassword());
            }

            _logger.Info($"[{AccountId}]: Invoking InitializeStateExecutionServices");
            _executionContextManager
            .InitializeStateExecutionServices(
                accountDescriptor.AccountId,
                accountDescriptor.SecretSpendKey,
                new Func <long, IStateTransactionsService, IStateClientCryptoService, CancellationToken, IUpdater>(
                    (accountId, stateTransactionsService, stateClientSryptoService, ct) =>
            {
                _clientCryptoService = stateClientSryptoService;
                return(this);
            }));

            Target = accountDescriptor.PublicSpendKey.ToHexString();

            cancellationToken.Register(() =>
            {
                _executionContextManager.UnregisterExecutionServices(AccountId);
            });
        }
예제 #4
0
        public HttpResponseMessage Post(AccountDTO accountDto)
        {
            if (accountDto.Account == "inventoryManager" && accountDto.Password == "inventoryManager")
            {
                accountDto.Password = "";
                accountDto.Role     = "inventory manager";
                accountDto.Token    = "aW52ZW50b3J5TWFuYWdlcjppbnZlbnRvcnlNYW5hZ2Vy";
                return(Request.CreateResponse(HttpStatusCode.OK, accountDto));
            }

            AccountBusiness accountBusiness = accountsService.Authenticate(accountDto.Account, accountDto.Password);

            if (accountBusiness != null)
            {
                if (accountBusiness.Password == "expired")
                {
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized));
                }

                accountDto.Password         = "";
                accountDto.Role             = "couple";
                accountDto.Token            = accountBusiness.Token;
                accountDto.PresentListId    = accountBusiness.ProductListId;
                accountDto.FirstName        = accountBusiness.HusbandName;
                accountDto.FirstNamePartner = accountBusiness.WifeName;
                accountDto.WeddingDate      = accountBusiness.WeddingDate;

                return(Request.CreateResponse(HttpStatusCode.OK, accountDto));
            }

            return(Request.CreateResponse(HttpStatusCode.NotFound));
        }
예제 #5
0
        public IActionResult Authenticate([FromBody] AccountDto accountDto)
        {
            var accountDescriptor = _accountsService.Authenticate(accountDto.AccountId, accountDto.Password);

            if (accountDescriptor == null)
            {
                return(Unauthorized(new { Message = "Failed to authenticate account" }));
            }

            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes(_appSettings.Secret);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, accountDto.AccountId.ToString()),
                    new Claim(ClaimTypes.NameIdentifier, accountDto.AccountId.ToString()),
                    new Claim(ClaimTypes.Role, "puser")
                }),
                Expires            = DateTime.UtcNow.AddDays(7),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token       = tokenHandler.CreateToken(tokenDescriptor);
            var tokenString = tokenHandler.WriteToken(token);

            return(Ok(new { accountDescriptor.AccountId, accountDescriptor.AccountType, accountDescriptor.AccountInfo, Token = tokenString, PublicSpendKey = accountDescriptor.PublicSpendKey.ToHexString(), PublicViewKey = accountDescriptor.PublicViewKey.ToHexString() }));
        }
예제 #6
0
        public void Initialize(IExecutionContextManager executionContextManager, CancellationToken cancellationToken)
        {
            _executionContextManager = executionContextManager;
            ConsentManagementSettings settings = _dataAccessService.GetConsentManagementSettings();

            if (settings == null)
            {
                settings = CreateNewConsentManagementServiceAccount();
            }

            AccountDescriptor accountDescriptor = _accountsService.Authenticate(settings.AccountId, GetDefaultConsentManagementPassword());

            if (accountDescriptor == null)
            {
                settings          = CreateNewConsentManagementServiceAccount();
                accountDescriptor = _accountsService.Authenticate(settings.AccountId, GetDefaultConsentManagementPassword());
                if (accountDescriptor == null)
                {
                    throw new Exception("ConsentManagementService initialization failed");
                }
            }

            _accountId = accountDescriptor.AccountId;

            _executionContextManager
            .InitializeUtxoExecutionServices(
                accountDescriptor.AccountId,
                accountDescriptor.SecretSpendKey,
                accountDescriptor.SecretViewKey,
                accountDescriptor.PwdHash,
                new Func <long, IUtxoClientCryptoService, CancellationToken, IUpdater>(
                    (accountId, clientCryptoService, ct) =>
            {
                _clientCryptoService = clientCryptoService;
                return(this);
            }));

            PublicSpendKey = accountDescriptor.PublicSpendKey.ToHexString();
            PublicViewKey  = accountDescriptor.PublicViewKey.ToHexString();

            cancellationToken.Register(() =>
            {
                _executionContextManager.UnregisterExecutionServices(_accountId);
            });
        }
예제 #7
0
        public async void Authenticate_CorrectLoginInput_ShouldValid()
        {
            //arrange
            var loginInput = new LoginRequest()
            {
                Email    = "*****@*****.**",
                Password = "******",
            };

            //act
            var accountInfo = await _accountService.Authenticate(loginInput);

            //assert
            var entity = _dbUsers.FirstOrDefault(u => u.Email.ToLower() == loginInput.Email.ToLower());

            Assert.NotNull(accountInfo);
            Assert.True(accountInfo.Id == entity.Id);
            Assert.True(accountInfo.Username == entity.Username);
            Assert.True(accountInfo.Email == entity.Email);
        }
예제 #8
0
        protected override void InitializeInner(CancellationToken cancellationToken)
        {
            _logger.Info($"Started {nameof(InitializeInner)}");

            _logger.Info($"There are {_externalIdps?.Length ?? 0} external IdPs");

            foreach (var externalIdp in _externalIdps)
            {
                _logger.Info($"Initializing {JsonConvert.SerializeObject(externalIdp)}");

                try
                {
                    var provider = _dataAccessService.GetExternalIdentityProvider(externalIdp.Name);
                    if (provider == null)
                    {
                        long accountId = CreateIdentityProviderAccount(externalIdp);

                        _dataAccessService.AddExternalIdentityProvider(externalIdp.Name, externalIdp.Alias, externalIdp.Description, accountId);
                        provider = _dataAccessService.GetExternalIdentityProvider(externalIdp.Name);
                    }

                    var accountDescriptor = _accountsService.Authenticate(provider.AccountId, GetDefaultIdpPassword(provider.Name));
                    if (accountDescriptor != null)
                    {
                        _logger.Info($"Account {externalIdp.Name} authenticated successfully");

                        if (externalIdp.AttributeDefinitions != null)
                        {
                            foreach (var item in externalIdp.AttributeDefinitions)
                            {
                                long rootAttributeSchemeId = _dataAccessService.AddAttributeToScheme(accountDescriptor.PublicSpendKey.ToHexString(), item.AttributeName, item.SchemeName, item.Alias, item.Description);
                                if (item.IsRoot)
                                {
                                    _dataAccessService.ToggleOnRootAttributeScheme(rootAttributeSchemeId);
                                }
                            }
                        }

                        _executionContextManager.InitializeStateExecutionServices(accountDescriptor.AccountId, accountDescriptor.SecretSpendKey);
                    }
                    else
                    {
                        _logger.Error($"Authentication of the account {externalIdp.Name} failed");
                    }

                    _logger.Info($"Finished {nameof(InitializeInner)}");
                }
                catch (Exception ex)
                {
                    _logger.Error($"Failed to initialize the External IdP {externalIdp.Name}", ex);
                }
            }
        }
예제 #9
0
        public IActionResult Authenticate([FromBody] AccountAuthenticateRequest body)
        {
            ResultCode resultCode; AccountModel account;

            (resultCode, account) = _service.Authenticate(body);

            Result error; int statusCode;

            (statusCode, error) = ResultHandler.GetStatusCodeAndResult(resultCode);

            GeneralResponse response = new GeneralResponse
            {
                Result = account,
                Error  = error,
            };

            return(StatusCode(statusCode, response));
        }
예제 #10
0
 public async Task Execute(string token, CreateAccountCommand command)
 {
     _AccountService.Authenticate(token);
     await _AccountService.Create(command);
 }
예제 #11
0
 public async Task <IActionResult> Login([FromBody] LoginRequest input)
 => await ReturnBadRequestIfThrowError(async() =>
 {
     var accInfo = await _accountService.Authenticate(input);
     return(_jwtService.GenerateToken(accInfo));;
 });
예제 #12
0
        public async Task <IActionResult> Transfer(DepositCommand deposit)
        {
            _Logger.LogInformation("Starting Transfer");

            Currency c = _TransactionDbContext.Currencies.SingleOrDefault(c => c.Symbol.ToUpper() == deposit.Currency.ToUpper());

            if (c == null)
            {
                c = new Currency()
                {
                    Symbol = deposit.Currency.ToUpper()
                };

                _TransactionDbContext.Currencies.Add(c);
            }
            string token = this.Request.Headers["Authorization"].ToString().Substring("Bearer ".Length);

            _AccountsService.Authenticate(token);

            AccountInfo account = await _AccountsService.GetAsync(deposit.AccountId);

            _Logger.LogInformation($"Transfer money to {account.Name}");

            if (deposit.Currency != account.Currency)
            {
                return(BadRequest("Deposit currency and account currency do not match"));
            }

            CashTransfer cashTransfer = new CashTransfer();

            cashTransfer.Currency  = c;
            cashTransfer.Date      = deposit.Date;
            cashTransfer.Amount    = deposit.Amount;
            cashTransfer.AccountId = account.Id;

            _TransactionDbContext.Add(cashTransfer);

            _TransactionDbContext.SaveChangesAsync();

            if (deposit.Amount > 0)
            {
                _Bus.SendAsync(new CashDepositedEvent()
                {
                    AccountId = deposit.AccountId,
                    Amount    = deposit.Amount,
                    Currency  = deposit.Currency,
                    Date      = deposit.Date,
                    Id        = Guid.NewGuid(),
                });
            }
            else
            {
                _Bus.SendAsync(new CashWithdrawnEvent()
                {
                    AccountId = deposit.AccountId,
                    Amount    = Math.Abs(deposit.Amount),
                    Currency  = deposit.Currency,
                    Date      = deposit.Date,
                    Id        = Guid.NewGuid(),
                });
            }

            return(StatusCode(StatusCodes.Status201Created));
        }