Exemple #1
0
 private void InitDbIdentity()
 {
     if (_dbId == null)
     {
         lock (_lockObject)
         {
             if (_dbId == null)
             {
                 var identity = Identities.FirstOrDefault();
                 if (identity == null)
                 {
                     var guid = Guid.NewGuid().ToByteArray();
                     identity = new IdentityEntity()
                     {
                         Data = guid
                     };
                     Identities.Add(identity);
                     SaveChanges();
                 }
                 _dbId = identity.Data;
                 Console.WriteLine($"SQLite ID:{_dbId.ToHexString()}");
             }
         }
     }
 }
Exemple #2
0
        /// <summary>
        /// Change the Username of an Identity.
        /// </summary>
        public void ChangeUsername(Guid identityId, string username)
        {
            CheckUsername(username);
            var identity = Identities.FirstOrDefault(x => x.Id == identityId);

            if (identity == null)
            {
                throw new Exception("Identity does not belong to this System.");
            }
            identity.ChangeUsername(username);
        }
Exemple #3
0
        public async void DeleteAccount(Account account)
        {
            Trace($"Delete {account}");

            var manager = Identities.FirstOrDefault(i => i.AccountID == account.ManagerID);

            if (manager != null)
            {
                await manager.DeleteAccount(account, Connection);
            }

            Uncache(account);
        }
        internal static void WebAppCallsWebApiImplementation(
            IServiceCollection services,
            IEnumerable <string>?initialScopes,
            Action <MicrosoftIdentityOptions> configureMicrosoftIdentityOptions,
            string openIdConnectScheme,
            Action <ConfidentialClientApplicationOptions>?configureConfidentialClientApplicationOptions)
        {
            // Ensure that configuration options for MSAL.NET, HttpContext accessor and the Token acquisition service
            // (encapsulating MSAL.NET) are available through dependency injection
            services.Configure(configureMicrosoftIdentityOptions);

            if (configureConfidentialClientApplicationOptions != null)
            {
                services.Configure(configureConfidentialClientApplicationOptions);
            }

            services.AddHttpContextAccessor();

            if (AppServicesAuthenticationInformation.IsAppServicesAadAuthenticationEnabled)
            {
                services.AddScoped <ITokenAcquisition, AppServicesAuthenticationTokenAcquisition>();
            }
            else
            {
                services.AddTokenAcquisition();

                services.AddOptions <OpenIdConnectOptions>(openIdConnectScheme)
                .Configure <IServiceProvider>((options, serviceProvider) =>
                {
                    options.ResponseType = OpenIdConnectResponseType.Code;
                    options.UsePkce      = false;

                    // This scope is needed to get a refresh token when users sign-in with their Microsoft personal accounts
                    // It's required by MSAL.NET and automatically provided when users sign-in with work or school accounts
                    options.Scope.Add(OidcConstants.ScopeOfflineAccess);
                    if (initialScopes != null)
                    {
                        foreach (string scope in initialScopes)
                        {
                            if (!options.Scope.Contains(scope))
                            {
                                options.Scope.Add(scope);
                            }
                        }
                    }

                    // Handling the auth redemption by MSAL.NET so that a token is available in the token cache
                    // where it will be usable from Controllers later (through the TokenAcquisition service)
                    var codeReceivedHandler = options.Events.OnAuthorizationCodeReceived;
                    options.Events.OnAuthorizationCodeReceived = async context =>
                    {
                        var tokenAcquisition = context !.HttpContext.RequestServices.GetRequiredService <ITokenAcquisitionInternal>();
                        await tokenAcquisition.AddAccountToCacheFromAuthorizationCodeAsync(context, options.Scope).ConfigureAwait(false);
                        await codeReceivedHandler(context).ConfigureAwait(false);
                    };

                    // Handling the token validated to get the client_info for cases where tenantId is not present (example: B2C)
                    var onTokenValidatedHandler     = options.Events.OnTokenValidated;
                    options.Events.OnTokenValidated = async context =>
                    {
                        string?clientInfo = context !.ProtocolMessage?.GetParameter(ClaimConstants.ClientInfo);

                        if (!string.IsNullOrEmpty(clientInfo))
                        {
                            ClientInfo?clientInfoFromServer = ClientInfo.CreateFromJson(clientInfo);

                            if (clientInfoFromServer != null && clientInfoFromServer.UniqueTenantIdentifier != null && clientInfoFromServer.UniqueObjectIdentifier != null)
                            {
                                context !.Principal !.Identities.FirstOrDefault()?.AddClaim(new Claim(ClaimConstants.UniqueTenantIdentifier, clientInfoFromServer.UniqueTenantIdentifier));
                                context !.Principal !.Identities.FirstOrDefault()?.AddClaim(new Claim(ClaimConstants.UniqueObjectIdentifier, clientInfoFromServer.UniqueObjectIdentifier));
                            }
                        }

                        await onTokenValidatedHandler(context).ConfigureAwait(false);
                    };

                    // Handling the sign-out: removing the account from MSAL.NET cache
                    var signOutHandler = options.Events.OnRedirectToIdentityProviderForSignOut;
                    options.Events.OnRedirectToIdentityProviderForSignOut = async context =>
                    {
                        // Remove the account from MSAL.NET token cache
                        var tokenAcquisition = context !.HttpContext.RequestServices.GetRequiredService <ITokenAcquisitionInternal>();
                        await tokenAcquisition.RemoveAccountAsync(context).ConfigureAwait(false);
                        await signOutHandler(context).ConfigureAwait(false);
                    };
                });
            }
        }
Exemple #5
0
 /// <summary>
 /// Find an Identity in the system by username.
 /// </summary>
 /// <param name="username"></param>
 /// <returns></returns>
 public Identity.Identity FindIdentity(string username)
 {
     return(Identities.FirstOrDefault(x => string.Equals(x.Username, username, StringComparison.InvariantCultureIgnoreCase)));
 }
Exemple #6
0
        private void OnNetworkEvent(NetworkEvent networkEvent)
        {
            switch (networkEvent)
            {
            case OriginatePendingEvent originate:
            {
                var identity = Identities
                               .FirstOrDefault(i => i.AccountID == originate.ManagerID);

                if (identity != null)
                {
                    var found = identity.Accounts
                                .Where(a => a.AccountID == originate.AccountID)
                                .FirstOrDefault();

                    if (found == null)
                    {
                        var account = new Account(originate.Name, originate.AccountID)
                        {
                            Stereotype = originate.Stereotype,
                            DelegateID = originate.DelegateID,
                        };

                        identity.ExpectOrigination(
                            account,
                            originate.OperationID,
                            originate.ContraAccountID,
                            originate.Amount);

                        OperationTaskflow.Update(originate.OperationID, TaskProgress.Acknowledged);
                    }
                }
            }
            break;

            case OriginateEvent originate:
            {
                if (IsTooOld(originate.BlockIndex))
                {
                    return;
                }

                if (accounts.ContainsKey(originate.AccountID))
                {
                    return;
                }

                var identity = Identities
                               .FirstOrDefault(i => i.AccountID == originate.ManagerID);

                if (identity != null)
                {
                    if (identity.Accounts
                        .FirstOrDefault(a => a.AccountID == originate.AccountID) is Account account)
                    {
                        // OriginatePendingEvent received before
                        account.CloseOperation(originate.OperationID, originate.Entry);
                    }
                    else
                    {
                        // switched on later
                        account = new Account(originate.Name, originate.AccountID)
                        {
                            Stereotype = originate.Stereotype,
                            DelegateID = originate.DelegateID,
                        };

                        identity.AddAccount(account);

                        account.AddEntry(originate.Entry);
                    }

                    account.Balance = originate.Balance;

                    account.State = TokenStoreState.Online;

                    Cache(account);

                    OperationTaskflow.Update(originate.OperationID, TaskProgress.Confirmed);
                }
            }
            break;

            case OriginationTimeoutEvent opTimeout:
            {
                var identity = Identities
                               .FirstOrDefault(i => i.AccountID == opTimeout.ManagerID);

                if (identity != null)
                {
                    if (identity.Accounts
                        .FirstOrDefault(a => a.AccountID == opTimeout.AccountID) is Account account)
                    {
                        account.CloseOperation(opTimeout.OperationID);
                        account.State = TokenStoreState.UnheardOf;
                    }

                    OperationTaskflow.Update(opTimeout.OperationID, TaskProgress.Timeout);
                }
            }
            break;

            case BalanceChangedEvent changeBalance:
            {
                if (IsTooOld(changeBalance.BlockIndex))
                {
                    return;
                }

                if (accounts.TryGetValue(changeBalance.AccountID, out TokenStore account))
                {
                    account.Balance = changeBalance.Balance;
                    account.UpdateState(changeBalance.State);
                    account.CloseOperation(changeBalance.OperationID, changeBalance.Entry);
                }

                OperationTaskflow.Update(changeBalance.OperationID, TaskProgress.Confirmed);
            }
            break;

            case TransactionPendingEvent transactionPending:
            {
                if (accounts.TryGetValue(transactionPending.AccountID, out TokenStore account))
                {
                    if (account.ExpectOperation(
                            transactionPending.OperationID,
                            transactionPending.ContraAccountID,
                            transactionPending.Amount))
                    {
                        account.State = TokenStoreState.Changing;

                        OperationTaskflow.Update(transactionPending.OperationID, TaskProgress.Acknowledged);
                    }
                }
            }
            break;

            case TransactionTimeoutEvent opTimeout:
            {
                Debug.Assert(opTimeout.AccountID != null);

                if (accounts.TryGetValue(opTimeout.AccountID, out TokenStore account))
                {
                    account.CloseOperation(opTimeout.OperationID);

                    OperationTaskflow.Update(opTimeout.OperationID, TaskProgress.Timeout);
                }
            }
            break;

            case ActivationPendingEvent activationPending:
            {
                if (accounts.TryGetValue(activationPending.IdentityID, out TokenStore account))
                {
                    if (account.ExpectOperation(
                            activationPending.OperationID,
                            null,
                            activationPending.Amount))
                    {
                        account.State = TokenStoreState.Changing;

                        OperationTaskflow.Update(activationPending.OperationID, TaskProgress.Acknowledged);
                    }
                }
            }
            break;

            case ActivationTimeoutEvent opTimeout:
            {
                Debug.Assert(opTimeout.IdentityID != null);

                if (accounts.TryGetValue(opTimeout.IdentityID, out TokenStore account))
                {
                    account.CloseOperation(opTimeout.OperationID);

                    OperationTaskflow.Update(opTimeout.OperationID, TaskProgress.Timeout);
                }
            }
            break;

            case ServiceEvent svc:
            {
                OnServiceEvent(svc);

                ServiceEventReceived?.Invoke(this, svc);
            }
            break;

            default:
                break;
            }
        }