Esempio n. 1
0
        private async Task <bool> UpdateApplicationProperties(string phone, string egn, Application app)
        {
            var isEgnValid = await validator.ValidateEGN(egn);

            var isPhoneValid = await validator.ValidatePhone(phone);

            if (isEgnValid && isPhoneValid)
            {
                app.EGN   = encrypter.Encrypt(egn);
                app.Phone = encrypter.Encrypt(phone);
                return(true);
            }
            return(false);
        }
Esempio n. 2
0
 protected override void MapEntityFields(ChargeCard domainObject, ChargeCardEntity entityToMapTo)
 {
     entityToMapTo.ChargeCardId   = domainObject.Id;
     entityToMapTo.Cvv            = _encrypter.Encrypt(domainObject.CVV);
     entityToMapTo.CardIssuer     = domainObject.CardIssuer;
     entityToMapTo.ExpirationDate = domainObject.ExpirationDate;
     entityToMapTo.IsDebitCard    = domainObject.IsDebit;
     entityToMapTo.NameOnCard     = domainObject.NameOnCard;
     entityToMapTo.Number         = _encrypter.Encrypt(domainObject.Number);
     entityToMapTo.TypeId         = (long)domainObject.TypeId;
     entityToMapTo.OrganizationRoleUserCreatorId = domainObject.DataRecorderMetaData.
                                                   DataRecorderCreator.Id;
     entityToMapTo.DateCreated = domainObject.DataRecorderMetaData.DateCreated;
     entityToMapTo.IsNew       = domainObject.Id <= 0;
 }
Esempio n. 3
0
        public IAccessToken Create(int userId)
        {
            // create the token
            var    token        = container.GetInstance <IAccessToken>();
            var    passwordHash = container.GetInstance <IPasswordHash>();
            string tokenHash;
            string encryptedUserId;

            byte[]   userIdSalt;
            DateTime issuedAt, refreshed;

            // check whether there is a token existing for this userId
            bool tokenExists = tokenStorage.VerifyTokenExistence(userId, out tokenHash, out issuedAt, out refreshed);

            if (tokenExists)
            {
                if (dateHelper.IsWithinTimeOutLimit(refreshed))
                {
                    // token is still valid, refresh the token to extend the timeout
                    if (!tokenStorage.RefreshToken(userId, tokenHash, dateHelper.Now))
                    {
                        throw new Exception("Failed to refresh existing the token");
                    }

                    token.IssuedAt  = issuedAt;
                    token.Token     = tokenHash;
                    encryptedUserId = null;
                    issuedAt        = new DateTime();
                    refreshed       = new DateTime();
                    return(token);
                }
            }

            // Create the token identifier
            Guid tokenId     = openGuid.New();
            var  hashedToken = passwordHash.CreateHash(tokenId.ToString());

            userIdSalt      = encrypter.GetSalt();
            encryptedUserId = encrypter.Encrypt(userId.ToString(), userIdSalt);
            issuedAt        = dateHelper.Now;

            //store the hashInfo
            if (!tokenStorage.StoreToken(userId, hashedToken, encryptedUserId, userIdSalt, issuedAt))
            {
                throw new Exception("Failed to store the session token");
            }

            // set the token for the user
            token.Token    = hashedToken.Hash;
            token.IssuedAt = issuedAt;

            //reset all information
            hashedToken.Dispose();
            userIdSalt      = null;
            encryptedUserId = null;
            passwordHash.Dispose();
            passwordHash = null;

            return(token);
        }
Esempio n. 4
0
        private Result register(User newUser, Specialization specialization)
        {
            if (loginAlreadyExists(newUser.Login))
            {
                return(new Result(false, Properties.Resources.LoginIsAlreadyTaken));
            }
            if (mailAlreadyExists(newUser.MailAddress))
            {
                return(new Result(false, Properties.Resources.MailIsAlreadyTaken));
            }

            var user = newUser;

            user.Password = encrypter.Encrypt(user.Password);

            // Muszę zapisać użytkownika do bazy, a potem go pobrać, żeby miał przydzielony przez bazę ID
            UsersRepository.Add(user);
            user = UsersRepository.GetList().Where(x => x.Login == user.Login && x.Password == user.Password).First();

            var userSpecialization = new UserSpecialization(user.Id, specialization.Id);

            UsersSpecializationsRepository.Add(userSpecialization);

            return(new Result(true));
        }
Esempio n. 5
0
        /// <inheritdoc />
        public async Task <bool> TryAddNewAdmin(int identifier, string token)
        {
            var query = $"EXECUTE dbo.AddAdmin @Token = '{_encrypter.Encrypt(token)}', @Identifier = {identifier}";

            try
            {
                await _connection.OpenAsync().ConfigureAwait(false);

                using (var command = new SqlCommand(query, _connection))
                {
                    await command.ExecuteNonQueryAsync().ConfigureAwait(false);
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
                if (Logger.IsErrorEnabled)
                {
                    Logger.Error(@"Не удалось добавить нового администратора!", exception);
                }
            }
            finally
            {
                _connection.Close();
            }

            return(await IsUserAdmin(identifier).ConfigureAwait(false));
        }
Esempio n. 6
0
        public override async Task <IViewProviderResult> BuildUpdateAsync(EmailSettings settings, IViewProviderContext context)
        {
            var model = new EmailSettingsViewModel();

            // Validate model
            if (!await context.Updater.TryUpdateModelAsync(model))
            {
                return(await BuildEditAsync(settings, context));
            }

            // Update settings
            if (context.Updater.ModelState.IsValid)
            {
                // Encrypt the password
                var username = model.SmtpSettings.UserName;
                var password = string.Empty;
                if (!string.IsNullOrWhiteSpace(model.SmtpSettings.Password))
                {
                    try
                    {
                        password = _encrypter.Encrypt(model.SmtpSettings.Password);
                    }
                    catch (Exception e)
                    {
                        if (_logger.IsEnabled(LogLevel.Error))
                        {
                            _logger.LogError($"There was a problem encrypting the SMTP server password. {e.Message}");
                        }
                    }
                }

                settings = new EmailSettings()
                {
                    SmtpSettings = new SmtpSettings()
                    {
                        DefaultFrom        = model.SmtpSettings.DefaultFrom,
                        Host               = model.SmtpSettings.Host,
                        Port               = model.SmtpSettings.Port,
                        UserName           = username,
                        Password           = password,
                        RequireCredentials = model.SmtpSettings.RequireCredentials,
                        EnableSsl          = model.SmtpSettings.EnableSsl,
                        PollingInterval    = model.SmtpSettings.PollInterval,
                        BatchSize          = model.SmtpSettings.BatchSize,
                        SendAttempts       = model.SmtpSettings.SendAttempts,
                        EnablePolling      = model.SmtpSettings.EnablePolling
                    }
                };

                var result = await _emailSettingsStore.SaveAsync(settings);

                if (result != null)
                {
                    // Recycle shell context to ensure changes take effect
                    _platoHost.RecycleShellContext(_shellSettings);
                }
            }

            return(await BuildEditAsync(settings, context));
        }
        public void EncryptFile(string source, string dest, EncryptionType enc)
        {
            string     plaintext  = System.IO.File.ReadAllText(source, Encoding.Unicode);
            IEncrypter encrypter  = GetEncrypter(enc);
            string     ciphertext = encrypter.Encrypt(plaintext);

            System.IO.File.WriteAllBytes(dest, TextUtils.StringToBytes(ciphertext));
        }
Esempio n. 8
0
        public async Task InsertUserIntoTheDb(User user)
        {
            string encryptedPassword = await _encrypter.Encrypt(user.Password);

            user.Password = encryptedPassword;
            _context.Users.Add(user);
            _context.SaveChanges();
        }
        public async Task <SynchronizationResult> Synchronize(IEnumerable <Account> localAccounts)
        {
            SynchronizationResult result = new SynchronizationResult()
            {
                HasChanges = false,
                Successful = false
            };

            if (encrypter != null && encrypter.IsInitialized)
            {
                await GetFileFromOneDrive();

                List <Account> mergedAccounts = new List <Account>();
                Account[]      remoteAccounts = new Account[0];

                if (!string.IsNullOrWhiteSpace(decrypted))
                {
                    remoteAccounts = JsonConvert.DeserializeObject <Account[]>(decrypted);
                }

                mergedAccounts.AddRange(localAccounts);

                foreach (Account account in remoteAccounts)
                {
                    if (!mergedAccounts.Contains(account))
                    {
                        mergedAccounts.Add(account);
                    }
                }

                string plainContents = JsonConvert.SerializeObject(mergedAccounts);
                string encrypted     = encrypter.Encrypt(plainContents);

                Stream stream = GenerateStreamFromString(encrypted);

                var item = await client.Drive.Special.AppRoot
                           .ItemWithPath(FILENAME)
                           .Content.Request()
                           .PutAsync <Item>(stream);

                result.Accounts   = mergedAccounts.ToArray();
                result.Successful = true;
            }

            return(result);
        }
Esempio n. 10
0
        public SC_USER SavePassword(SC_USER obj)
        {
            var currentUser = _general.Get <SC_USER>(obj.IdUser);

            currentUser.Password = _encrypter.Encrypt(obj.Password);
            currentUser          = _general.Update(currentUser);
            _session.Set(Strings.Authorization.UserSessionKey, currentUser);
            return(currentUser);
        }
Esempio n. 11
0
        public void Set <T>(string key, T value)
        {
            ValidationUtils.ArgumentNotNull(key, nameof(key));
            ValidationUtils.ArgumentNotNull(value, nameof(value));

            string data = _serializer.Serialize(value);

            data = _encrypter.Encrypt(data);
            _storage.Write(key, data);
        }
Esempio n. 12
0
        public override async Task <IViewProviderResult> BuildUpdateAsync(PlatoGoogleSettings settings, IViewProviderContext context)
        {
            var model = new GoogleSettingsViewModel();

            // Validate model
            if (!await context.Updater.TryUpdateModelAsync(model))
            {
                return(await BuildEditAsync(settings, context));
            }

            // Update settings
            if (context.Updater.ModelState.IsValid)
            {
                // Encrypt the secret
                var secret = string.Empty;
                if (!string.IsNullOrWhiteSpace(model.ClientSecret))
                {
                    try
                    {
                        secret = _encrypter.Encrypt(model.ClientSecret);
                    }
                    catch (Exception e)
                    {
                        if (_logger.IsEnabled(LogLevel.Error))
                        {
                            _logger.LogError(e, $"There was a problem encrypting the Google client secret. {e.Message}");
                        }
                    }
                }

                // Create the model
                settings = new PlatoGoogleSettings()
                {
                    ClientId     = model.ClientId,
                    ClientSecret = secret,
                    CallbackPath = model.CallbackPath,
                    TrackingId   = model.TrackingId
                };

                // Persist the settings
                var result = await _googleSettingsStore.SaveAsync(settings);

                if (result != null)
                {
                    // Recycle shell context to ensure changes take effect
                    _platoHost.RecycleShellContext(_shellSettings);
                }
            }

            return(await BuildEditAsync(settings, context));
        }
Esempio n. 13
0
        public override async Task <IViewProviderResult> BuildUpdateAsync(PlatoSlackSettings settings, IViewProviderContext context)
        {
            var model = new SlackSettingsViewModel();

            // Validate model
            if (!await context.Updater.TryUpdateModelAsync(model))
            {
                return(await BuildEditAsync(settings, context));
            }

            // Update settings
            if (context.Updater.ModelState.IsValid)
            {
                // Encrypt the secret
                var webHookUrl        = string.Empty;
                var accessTokenSecret = string.Empty;

                if (!string.IsNullOrWhiteSpace(model.WebHookUrl))
                {
                    try
                    {
                        webHookUrl = _encrypter.Encrypt(model.WebHookUrl);
                    }
                    catch (Exception e)
                    {
                        if (_logger.IsEnabled(LogLevel.Error))
                        {
                            _logger.LogError(e, $"There was a problem encrypting the Slack Web Hook URL. {e.Message}");
                        }
                    }
                }

                // Create the model
                settings = new PlatoSlackSettings()
                {
                    WebHookUrl = webHookUrl
                };

                // Persist the settings
                var result = await _TwitterSettingsStore.SaveAsync(settings);

                if (result != null)
                {
                    // Recycle shell context to ensure changes take effect
                    _platoHost.RecycleShellContext(_shellSettings);
                }
            }

            return(await BuildEditAsync(settings, context));
        }
        public async Task AddNewlyReceivedMessage(string gmailId, string body, string senderEmail, ICollection <int> attachmentData)
        {
            if (await this.context.Applications.AnyAsync(u => u.GmailId == gmailId))
            {
                return;
            }

            var app = new Application
            {
                GmailId           = gmailId,
                Body              = encrypter.Encrypt(body),
                Email             = encrypter.Encrypt(senderEmail),
                Received          = DateTime.UtcNow,
                ApplicationStatus = ApplicationStatus.NotReviewed,
                LastChange        = DateTime.UtcNow,
                AttachmentSize    = attachmentData.Take(1).First(),
                AttachmentsCount  = attachmentData.Skip(1).Take(1).First()
            };

            await this.context.Applications.AddAsync(app);

            await this.context.SaveChangesAsync();
        }
Esempio n. 15
0
        public void ToStream(object data, ref BytePacker packer, IEncrypter encrypter)
        {
            if (Compression == Compression.LZ4)
            {
                int        size      = converter.GetDataSize(data);
                byte[]     buf       = new byte[size];
                BytePacker lz4packer = new BytePacker(buf);
                converter.Serialize(lz4packer, data);

                //Encrypt
                if (encrypter != null)
                {
                    buf = encrypter.Encrypt(buf);
                }

                byte[] encoded = LZ4Pickler.Pickle(buf);
                byteArrayConverter.Serialize(packer, encoded);
            }
            else
            {
                //Encrypt
                if (encrypter != null)
                {
                    int        size      = converter.GetDataSize(data);
                    byte[]     buf       = new byte[size];
                    BytePacker encpacker = new BytePacker(buf);
                    converter.Serialize(encpacker, data);

                    buf = encrypter.Encrypt(buf);
                    encArrayConverter.Serialize(packer, buf);
                }
                else
                {
                    converter.Serialize(packer, data);
                }
            }
        }
Esempio n. 16
0
        public override async Task <IViewProviderResult> BuildUpdateAsync(DemoSettings settings, IViewProviderContext context)
        {
            var model = new DemoSettingsViewModel();

            // Validate model
            if (!await context.Updater.TryUpdateModelAsync(model))
            {
                return(await BuildEditAsync(settings, context));
            }

            // Update settings
            if (context.Updater.ModelState.IsValid)
            {
                // Encrypt the password
                var adminPassword = string.Empty;
                if (!string.IsNullOrWhiteSpace(model.AdminPassword))
                {
                    try
                    {
                        adminPassword = _encrypter.Encrypt(model.AdminPassword);
                    }
                    catch (Exception e)
                    {
                        if (_logger.IsEnabled(LogLevel.Error))
                        {
                            _logger.LogError(e, $"There was a problem encrypting the demo administrator password. {e.Message}");
                        }
                    }
                }

                // Create the model
                settings = new DemoSettings()
                {
                    AdminUserName = model.AdminUserName,
                    AdminPassword = adminPassword
                };

                // Persist the settings
                var result = await _demoSettingsStore.SaveAsync(settings);

                if (result != null)
                {
                    // Recycle shell context to ensure changes take effect
                    _platoHost.RecycleShellContext(_shellSettings);
                }
            }

            return(await BuildEditAsync(settings, context));
        }
Esempio n. 17
0
        private Result logIn(string login, string password)
        {
            var hashedPassword = encrypter.Encrypt(password);

            var userList         = UsersRepository.GetList().Where(x => x.Login == login && x.Password == hashedPassword).ToList();
            var anyMatchingUsers = userList.Count > 0;

            if (!anyMatchingUsers)
            {
                Logger.Warning(string.Format(Properties.Resources.FailedLoginAttempt, login));
                return(new Result(false, Properties.Resources.WrongLoginOrPassword));
            }

            session.User = userList.First();
            Logger.Info(string.Format(Properties.Resources.SuccessfulLoginAttempt, login));
            return(new Result(true));
        }
        public async Task <string> Authorize(string email, string password, CancellationToken cancellation)
        {
            User user = await _repo.FindUserByEmailAsync(email, cancellation);

            string encryptedPassword = await _encrypter.Encrypt(password);

            if ((user is not null) && (user.Password.Equals(encryptedPassword)))
            {
                var TokenHandler    = new JwtSecurityTokenHandler();
                var TokenKey        = Encoding.ASCII.GetBytes(key);
                var TokenDescriptor = new SecurityTokenDescriptor
                {
                    Subject = new ClaimsIdentity(new Claim[]
                    {
                        new Claim(ClaimTypes.NameIdentifier, user.Id.ToString())
                    }),
                    Expires            = DateTime.Now.AddDays(1),
                    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(TokenKey), SecurityAlgorithms.HmacSha256Signature)
                };
                var token = TokenHandler.CreateToken(TokenDescriptor);
                return(TokenHandler.WriteToken(token));
            }
Esempio n. 19
0
        public async Task CreateAsync(string box, string key, object value, string author, string encryptionKey)
        {
            var entryBox = await _boxRepository.GetAsync(box);

            if (entryBox == null)
            {
                throw new ArgumentException($"Box '{box}' has not been found.");
            }

            if (entryBox.Entries.Count() >= _featureSettings.EntriesPerBoxLimit)
            {
                throw new InvalidOperationException($"Box: '{box}' already contains " +
                                                    $"{_featureSettings.EntriesPerBoxLimit} entries.");
            }

            var randomSecureKey   = _encrypter.GetRandomSecureKey();
            var salt              = _encrypter.GetSalt(randomSecureKey);
            var serializedValue   = JsonConvert.SerializeObject(value);
            var encryptedValue    = _encrypter.Encrypt(serializedValue, salt, encryptionKey);
            var entry             = new Entry(key, encryptedValue, salt, author);
            var deserializedEntry = JsonConvert.SerializeObject(entry);
            var entrySize         = Encoding.UTF8.GetByteCount(deserializedEntry);

            if (entrySize > _featureSettings.EntrySizeBytesLimit)
            {
                throw new InvalidOperationException($"Entry size is too big: {entrySize} bytes " +
                                                    $"(limit: {_featureSettings.EntrySizeBytesLimit} bytes).");
            }

            await DeleteAsync(box, key);

            entryBox.AddEntry(entry);
            await _boxRepository.UpdateAsync(entryBox);

            Logger.Information($"Eentry '{key}' was added to the box '{box}'.");
        }
Esempio n. 20
0
        public bool LoginByUsernameAndPassword(string username, string password)
        {
            var encryptedPassword = _encrypter.Encrypt(password);
            var lstUser           = _general.GetAll <SC_USER>();
            var userModel         = lstUser.Where(r => r.UserName == username && r.Password == encryptedPassword && r.Active && r.Deleted == false && r.FailedLoginCount < 4).FirstOrDefault();

            if (userModel != null)
            {
                _sessionProvider.Set(Strings.Authorization.UserSessionKey, userModel);

                _sessionProvider.Set(Strings.Authorization.IsLoginSessionKey, false);

                userModel.FailedLoginCount = 0;
                _repository.Update(userModel);
                //_repository.SetContext(userModel.IdUser);
                _logger.LogInformation(new LogModel
                {
                    ActionName     = "Login",
                    ControllerName = "LoginController",
                    RequestUrl     = "/Login",
                    ShortMessage   = Strings.Messages.LoginPage.Login(userModel)
                });
            }
            else
            {
                var user2 = lstUser.Where(r => r.UserName == username && r.Deleted == false).FirstOrDefault();

                if (user2 != null)
                {
                    _logger.LogInformation(new LogModel
                    {
                        ActionName     = "Login",
                        ControllerName = "LoginController",
                        RequestUrl     = "/Login",
                        ShortMessage   = Strings.Messages.LoginPage.FailedLogin(user2)
                    });

                    if (user2.FailedLoginCount < 4)
                    {
                        user2.FailedLoginCount++;
                        _repository.Update(user2);
                        return(false);
                    }
                    else
                    {
                        user2.Active = false;
                        _repository.Update(user2);
                        return(false);
                    }
                }
                else
                {
                    return(false);
                }
            }

            _cookieProvider.SetCookie(Strings.CookieKeys.UserName, userModel.UserName, TimeSpan.FromDays(1));
            _cookieProvider.SetCookie(Strings.CookieKeys.IdUser, userModel.IdUser.ToString(), TimeSpan.FromDays(1));

            return(true);
        }
Esempio n. 21
0
 public string Encrypt(string obj)
 {
     return(_enc.Encrypt(obj));
 }
Esempio n. 22
0
        /// <summary>
        /// Сохранение токена.
        /// </summary>
        /// <param name="token">Токен.</param>
        /// <param name="userStat">Разрешено читать статистику пользователей.</param>
        /// <param name="questionStat">Разрешено читать статистику по вопросам.</param>
        private void SaveToken(string token, bool userStat, bool questionStat)
        {
            var uStat = userStat ? 1 : 0;
            var qStat = questionStat ? 1 : 0;
            var query = $"INSERT INTO dbo.Tokens(Token, UserStat, QuestionsStat) VALUES('{_encrypter.Encrypt(token)}', {uStat}, {qStat})";

            try
            {
                _connection.Open();
                using (var command = new SqlCommand(query, _connection))
                {
                    command.ExecuteNonQuery();
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
            }
            finally
            {
                _connection.Close();
            }
        }
Esempio n. 23
0
        public override async Task <IViewProviderResult> BuildUpdateAsync(ShellSettings settings, IViewProviderContext context)
        {
            var model = new EditTenantViewModel();

            if (!await context.Updater.TryUpdateModelAsync(model))
            {
                return(await BuildEditAsync(settings, context));
            }

            if (context.Updater.ModelState.IsValid)
            {
                // Ensure password
                if (model.SmtpSettings != null)
                {
                    if (!string.IsNullOrWhiteSpace(model.SmtpSettings.Password))
                    {
                        try
                        {
                            model.SmtpSettings.Password = _encrypter.Encrypt(model.SmtpSettings.Password);
                        }
                        catch (Exception e)
                        {
                            if (_logger.IsEnabled(LogLevel.Error))
                            {
                                _logger.LogError($"There was a problem encrypting the SMTP server password. {e.Message}");
                            }
                        }
                    }
                }

                var setupContext = new TenantSetUpContext()
                {
                    SiteName                 = model.SiteName,
                    Location                 = model.Location,
                    DatabaseProvider         = "SqlClient",
                    DatabaseConnectionString = model.ConnectionString,
                    AdminUsername            = model.UserName,
                    AdminEmail               = model.Email,
                    AdminPassword            = model.Password,
                    RequestedUrlHost         = model.RequestedUrlHost,
                    RequestedUrlPrefix       = model.RequestedUrlPrefix,
                    State         = model.State,
                    OwnerId       = model.OwnerId,
                    CreatedDate   = model.IsNewTenant ? DateTimeOffset.Now : model.CreatedDate,
                    ModifiedDate  = model.IsNewTenant ? model.ModifiedDate : DateTimeOffset.Now,
                    EmailSettings = new EmailSettings()
                    {
                        SmtpSettings = model.SmtpSettings
                    },
                    Errors = new Dictionary <string, string>()
                };

                if (!model.TablePrefixPreset)
                {
                    setupContext.DatabaseTablePrefix = model.TablePrefix;
                }

                // Install or update tenant
                var result = model.IsNewTenant
                    ? await _tenantSetUpService.InstallAsync(setupContext)
                    : await _tenantSetUpService.UpdateAsync(setupContext);

                // Report any errors
                if (!result.Succeeded)
                {
                    if (_logger.IsEnabled(LogLevel.Information))
                    {
                        if (model.IsNewTenant)
                        {
                            _logger.LogInformation($"Set-up of tenant '{setupContext.SiteName}' failed with the following errors...");
                        }
                        else
                        {
                            _logger.LogInformation($"Update of tenant '{setupContext.SiteName}' failed with the following errors...");
                        }
                    }

                    foreach (var error in result.Errors)
                    {
                        if (_logger.IsEnabled(LogLevel.Information))
                        {
                            _logger.LogInformation(error.Code + " " + error.Description);
                        }
                        context.Updater.ModelState.AddModelError(error.Code, error.Description);
                    }
                }
            }

            return(await BuildEditAsync(settings, context));
        }
Esempio n. 24
0
 //takes input and encrypts it
 public String Encrypt(String input)
 {
     return(worker.Encrypt(input));
 }
Esempio n. 25
0
        public override async Task <IViewProviderResult> BuildUpdateAsync(DefaultTenantSettings settings, IViewProviderContext context)
        {
            var model = new EditTenantSettingsViewModel();

            // Validate model
            if (!await context.Updater.TryUpdateModelAsync(model))
            {
                return(await BuildEditAsync(settings, context));
            }

            // Update settings
            if (context.Updater.ModelState.IsValid)
            {
                // Encrypt connection string
                var connectionString = string.Empty;
                if (!string.IsNullOrWhiteSpace(model.ConnectionString))
                {
                    try
                    {
                        connectionString = _encrypter.Encrypt(model.ConnectionString);
                    }
                    catch (Exception e)
                    {
                        if (_logger.IsEnabled(LogLevel.Error))
                        {
                            _logger.LogError($"There was a problem encrypting the default tenant connection string. {e.Message}");
                        }
                    }
                }

                // Encrypt password
                var password = string.Empty;
                if (!string.IsNullOrWhiteSpace(model.SmtpSettings.Password))
                {
                    try
                    {
                        password = _encrypter.Encrypt(model.SmtpSettings.Password);
                    }
                    catch (Exception e)
                    {
                        if (_logger.IsEnabled(LogLevel.Error))
                        {
                            _logger.LogError($"There was a problem encrypting the SMTP server password. {e.Message}");
                        }
                    }
                }

                settings = new DefaultTenantSettings()
                {
                    ConnectionString = connectionString,
                    TablePrefix      = model.TablePrefix,
                    SmtpSettings     = new SmtpSettings()
                    {
                        DefaultFrom        = model.SmtpSettings.DefaultFrom,
                        Host               = model.SmtpSettings.Host,
                        Port               = model.SmtpSettings.Port,
                        UserName           = model.SmtpSettings.UserName,
                        Password           = password,
                        RequireCredentials = model.SmtpSettings.RequireCredentials,
                        EnableSsl          = model.SmtpSettings.EnableSsl
                    }
                };

                var result = await _tenantSettingsStore.SaveAsync(settings);

                if (result != null)
                {
                    // Recycle shell context to ensure changes take effect
                    _platoHost.RecycleShell(_shellSettings);
                }
            }

            return(await BuildEditAsync(settings, context));
        }