private async Task <List <SecurityContractDefaultConfigurationUser> > RetrieveDefaultConfigUsers()
        {
            var contractUserList   = new List <SecurityContractDefaultConfigurationUser>();
            List <UserModel> users = await userRepository.GetListAsync();

            foreach (var user in users.OrderBy(o => o.SysPeriod.LowerBound))
            {
                logger.Debug($"Retrieving default configuration contract definition for User [{user.UserName}].");

                var contractUser = new SecurityContractDefaultConfigurationUser()
                {
                    Uuid                   = new Guid(user.Id),
                    Username               = user.UserName,
                    Name                   = user.FirstName,
                    Surname                = user.Surname,
                    Email                  = user.Email,
                    HashedPassword         = user.PasswordHash,
                    IsDeleted              = user.IsDeleted,
                    DeletedTime            = user.DeletedTime,
                    LdapAuthenticationMode = user.LdapAuthenticationMode?.Name,
                    Avatar                 = user.Avatar == null ? null : Convert.ToBase64String(user.Avatar),
                    Roles                  = new List <string>()
                };

                foreach (var role in user.UserRoles.OrderBy(o => o.Role.SysPeriod.LowerBound))
                {
                    contractUser.Roles.Add(role.Role.Name);
                }

                contractUserList.Add(contractUser);
            }

            return(contractUserList);
        }
        private async Task ApplyRolesToDefaultUser(SecurityContractDefaultConfigurationUser defaultUser, UserModel defaultUserToApply, Guid updatedById)
        {
            if (defaultUser.Roles != null && defaultUser.Roles.Count > 0)
            {
                foreach (var roleToApply in defaultUser.Roles)
                {
                    logger.Debug($"Attempting to add role '{roleToApply}' to user '{defaultUser.Username}'");
                    // Ensure the role actually exists first. If it does not, ignore the role assignment.
                    var existingRole = await roleRepository.GetByNameAsync(roleToApply);

                    if (existingRole == null)
                    {
                        logger.Warn($"Role '{roleToApply}' does not exists within the database. NOT applying it to user '{defaultUser.Username}'.");
                        break;
                    }

                    logger.Debug($"Role '{roleToApply}' does exist within the database. Assigning it to user '{defaultUser.Username}'.");
                    defaultUserToApply.UserRoles.Add(new UserRoleModel
                    {
                        User      = defaultUserToApply,
                        Role      = existingRole,
                        ChangedBy = updatedById
                    });
                }
            }
        }
        private async Task ApplyLdapAuthModeToDefaultUser(SecurityContractDefaultConfigurationUser defaultUser, UserModel defaultUserToApply)
        {
            if (!string.IsNullOrWhiteSpace(defaultUser.LdapAuthenticationMode))
            {
                logger.Debug($"Attempting to add Ldap Auth mode '{defaultUser.LdapAuthenticationMode}' to user '{defaultUser.Username}'");
                // Ensure the Ldap Auth mode actually exists first. If it does not, ignore the Ldap Auth mode assignment.
                var existingLdapAuthMode = await ldapAuthenticationModeRepository.GetByNameAsync(defaultUser.LdapAuthenticationMode);

                if (existingLdapAuthMode == null)
                {
                    logger.Warn($"Ldap Auth mode '{defaultUser.LdapAuthenticationMode}' does not exists within the database. NOT applying it to user '{defaultUser.Username}'.");
                    return;
                }

                logger.Debug($"Ldap Auth mode '{defaultUser.LdapAuthenticationMode}' does exist within the database. Assigning it to user '{defaultUser.Username}'.");
                defaultUserToApply.LdapAuthenticationMode   = existingLdapAuthMode;
                defaultUserToApply.LdapAuthenticationModeId = existingLdapAuthMode.Id;
            }
        }
        private async Task ApplyIndividualDefaultUser(SecurityContractDefaultConfigurationUser defaultUser, Guid updatedById)
        {
            logger.Debug($"Operating on default user '{defaultUser.Username}'.");
            var defaultUserToApply = new UserModel();

            bool newUser = false;
            // Get the user with all it's associated relations, as we are going to be tweaking some of them, especially any assigned roles.
            var existingUser = await userRepository.GetByUsernameAsync(defaultUser.Username, true);

            if (existingUser != null)
            {
                logger.Debug($"Default user: '******' already exist. Updating it.");
                defaultUserToApply = existingUser;
            }
            else
            {
                logger.Debug($"Default user: '******' does not exist. Creating it.");
                newUser = true;
                // We can also bind the user's UUID here, but only if one is supplied. We should not bind it on any user updates, as UUIDs associated with users cannot be changed!
                // Recall: The user ID within the dotnet Identity table is purposely a string. Convert the GUID representation accordingly.
                if (defaultUser.Uuid != Guid.Empty)
                {
                    defaultUserToApply.Id = defaultUser.Uuid.ToString();
                }
            }

            // Map the base components.
            defaultUserToApply.Email                = defaultUser.Email.Trim();
            defaultUserToApply.NormalizedEmail      = defaultUserToApply.Email.ToUpper();
            defaultUserToApply.EmailConfirmed       = true;
            defaultUserToApply.PhoneNumber          = defaultUser.PhoneNumber;
            defaultUserToApply.PhoneNumberConfirmed = (defaultUserToApply.PhoneNumber != null);
            defaultUserToApply.UserName             = defaultUser.Username.Trim();
            defaultUserToApply.NormalizedUserName   = defaultUserToApply.UserName.ToUpper();
            defaultUserToApply.FirstName            = defaultUser.Name;
            defaultUserToApply.Surname              = defaultUser.Surname;
            defaultUserToApply.IsDeleted            = defaultUser.IsDeleted;
            defaultUserToApply.DeletedTime          = defaultUser.DeletedTime;
            defaultUserToApply.ChangedBy            = updatedById;

            if (!string.IsNullOrEmpty(defaultUser.Avatar))
            {
                defaultUserToApply.Avatar = Convert.FromBase64String(defaultUser.Avatar);
            }

            // Overwrite any potentially assigned roles, as the declarative representation in the defaultUser is the authoratative version and must overwite any existing state.
            defaultUserToApply.UserRoles = new List <UserRoleModel>();

            await ApplyRolesToDefaultUser(defaultUser, defaultUserToApply, updatedById);
            await ApplyLdapAuthModeToDefaultUser(defaultUser, defaultUserToApply);

            if (newUser)
            {
                logger.Debug($"Persisting new user '{defaultUser.Username}' into the database.");

                if (string.IsNullOrWhiteSpace(defaultUser.HashedPassword))
                {
                    await userRepository.CreateAsync(defaultUserToApply, defaultUser.Password, isPlainTextPassword : true);
                }
                else
                {
                    await userRepository.CreateAsync(defaultUserToApply, defaultUser.HashedPassword, isPlainTextPassword : false);
                }
            }
            else
            {
                logger.Debug($"Updating existing user '{defaultUser.Username}' into the database.");
                await userRepository.UpdateAsync(defaultUserToApply);
            }
        }