public GigyaSettingsResponseModel Save(GigyaSettingsModel model)
        {
            var response = new GigyaSettingsResponseModel();

            if (!ModelState.IsValid)
            {
                var errorList = ModelState.Values.SelectMany(m => m.Errors)
                                .Select(e => e.ErrorMessage)
                                .ToList();

                response.Error = string.Join(" ", errorList);
                _logger.Error(response.Error);
                return(response);
            }

            var settingsHelper = new Umbraco.Module.v621.Helpers.GigyaSettingsHelper();

            if (model.Inherited && model.Id > 0)
            {
                settingsHelper.Delete(model.Id);
                response.Success = true;

                // return global settings to refresh client
                var globalData  = settingsHelper.Get(model.Id);
                var globalModel = GetModel(model.Id, globalData);
                response.Settings = globalModel;
                return(response);
            }

            var settings = settingsHelper.GetRaw(model.Id);

            // update all fields
            settings.ApiKey           = model.ApiKey;
            settings.DebugMode        = model.DebugMode;
            settings.ApplicationKey   = model.ApplicationKey;
            settings.DataCenter       = !string.IsNullOrEmpty(model.DataCenter) && model.DataCenter != Core.Constants.DataCenter.Other ? model.DataCenter : model.DataCenterOther;
            settings.EnableRaas       = model.EnableRaas;
            settings.GlobalParameters = model.GlobalParameters;
            settings.Language         = !string.IsNullOrEmpty(model.Language.Code) && model.Language.Code != Core.Constants.Languages.Other ? model.Language.Code : model.LanguageOther;
            settings.LanguageFallback = model.LanguageFallback.Code;
            settings.MappingFields    = JsonConvert.SerializeObject(model.MappingFields);
            settings.RedirectUrl      = model.RedirectUrl;
            settings.LogoutUrl        = model.LogoutUrl;
            settings.SessionTimeout   = model.SessionTimeout;

            // application secret that we will use to validate the settings - store this in a separate var as it's unencrypted
            string plainTextApplicationSecret = string.Empty;

            // check if user can view application secret
            if (!string.IsNullOrEmpty(model.ApplicationSecret))
            {
                plainTextApplicationSecret = model.ApplicationSecret;
                var canViewApplicationSecret = (UmbracoUser.UserType.Name == Constants.UserTypes.Admin) || User.IsInRole(Constants.Roles.GigyaAdmin);
                if (canViewApplicationSecret)
                {
                    if (!Encryptor.IsConfigured)
                    {
                        response.Error = "Encryption key not specified. Refer to installation guide.";
                        _logger.Error(response.Error);
                        return(response);
                    }
                    settings.ApplicationSecret = Encryptor.Encrypt(model.ApplicationSecret);
                }
            }

            if (string.IsNullOrEmpty(plainTextApplicationSecret) && Encryptor.IsConfigured && !string.IsNullOrEmpty(settings.ApplicationSecret))
            {
                plainTextApplicationSecret = TryDecryptApplicationSecret(settings.ApplicationSecret, false);
                if (string.IsNullOrEmpty(plainTextApplicationSecret))
                {
                    response.Error = "Application Secret could not be decrypted. Please re-enter it.";
                    _logger.Error(response.Error);
                    return(response);
                }
            }

            var mappedSettings = Map(settings);

            mappedSettings.ApplicationSecret = plainTextApplicationSecret;

            try
            {
                // validate input
                settingsHelper.Validate(mappedSettings);
            }
            catch (Exception e)
            {
                _logger.Error(e.Message);
                response.Error = e.Message;
                return(response);
            }

            // verify settings are correct
            var apiHelper    = new GigyaApiHelper(settingsHelper, _logger);
            var testResponse = apiHelper.VerifySettings(mappedSettings, plainTextApplicationSecret);

            if (testResponse.GetErrorCode() != 0)
            {
                var gigyaErrorDetail = testResponse.GetString("errorDetails", string.Empty);
                var message          = testResponse.GetErrorMessage();
                if (!string.IsNullOrEmpty(gigyaErrorDetail))
                {
                    message = string.Concat(message, ". ", gigyaErrorDetail);
                }

                response.Error = message;
                return(response);
            }

            settingsHelper.Save(settings);

            response.Success = true;
            return(response);
        }
        /// <summary>
        /// Save values from basic settings page
        /// </summary>
        public void Save(Guid id)
        {
            using (var context = GigyaContext.Get())
            {
                // get settings to update
                var settings = context.Settings.FirstOrDefault(i => i.SiteId == id) ?? new GigyaSitefinityModuleSettings {
                    SiteId = id
                };

                // update all fields
                settings.ApiKey           = this.ApiKey.Trim();
                settings.DebugMode        = this.DebugMode;
                settings.ApplicationKey   = this.ApplicationKey.Trim();
                settings.DataCenter       = !string.IsNullOrEmpty(this.DataCenter) ? this.DataCenter : this.DataCenterOther;
                settings.EnableRaas       = this.EnableRaas;
                settings.GlobalParameters = this.GlobalParameters;
                settings.Language         = !string.IsNullOrEmpty(this.Language) ? this.Language : this.LanguageOther;
                settings.LanguageFallback = this.LanguageFallback;
                settings.MappingFields    = this.MappingFields;
                settings.RedirectUrl      = this.RedirectUrl;
                settings.LogoutUrl        = this.LogoutUrl;
                settings.SessionTimeout   = this.SessionTimeout;
                settings.SessionProvider  = this.SessionProvider;
                settings.GigyaSessionMode = this.GigyaSessionMode;

                if (settings.SessionProvider == GigyaSessionProvider.Gigya)
                {
                    switch (settings.GigyaSessionMode)
                    {
                    case GigyaSessionMode.Session:
                        settings.SessionTimeout = 0;
                        break;

                    case GigyaSessionMode.Forever:
                        settings.SessionTimeout = -2;
                        break;
                    }
                }

                var mappingFields = JsonConvert.DeserializeObject <List <MappingField> >(MappingFields);
                if (mappingFields == null || !mappingFields.Any())
                {
                    throw new ArgumentException(Constants.Errors.UIDFieldRequired);
                }

                // validate that there is a mapping field for UID
                var usernameMappingExists = mappingFields.Any(i => i.GigyaFieldName == Constants.GigyaFields.UserId);
                if (!usernameMappingExists)
                {
                    throw new ArgumentException(Constants.Errors.UIDFieldRequired);
                }

                if (mappingFields.Any(i => string.IsNullOrEmpty(i.GigyaFieldName)))
                {
                    throw new ArgumentException(Constants.Errors.GigyaFieldNameRequired);
                }

                if (mappingFields.Any(i => string.IsNullOrEmpty(i.CmsFieldName)))
                {
                    throw new ArgumentException(Constants.Errors.CmsFieldNameRequired);
                }

                // application secret that we will use to validate the settings - store this in a separate var as it's unencrypted
                string plainTextApplicationSecret = string.Empty;

                // check if user can view application secret
                if (!string.IsNullOrEmpty(ApplicationSecret))
                {
                    plainTextApplicationSecret = ApplicationSecret.Trim();
                    var identity = ClaimsManager.GetCurrentIdentity();
                    var canViewApplicationSecret = identity.IsAuthenticated && Gigya.Module.Connector.Admin.Roles.HasRole(identity);
                    if (canViewApplicationSecret)
                    {
                        if (!Encryptor.IsConfigured)
                        {
                            throw new ArgumentException("Encryption key not specified. Refer to installation guide.");
                        }

                        settings.ApplicationSecret = Encryptor.Encrypt(plainTextApplicationSecret);
                    }
                }

                if (string.IsNullOrEmpty(plainTextApplicationSecret) && Encryptor.IsConfigured && !string.IsNullOrEmpty(settings.ApplicationSecret))
                {
                    plainTextApplicationSecret = TryDecryptApplicationSecret(settings.ApplicationSecret);
                }

                var mappedSettings = Map(settings);

                // validate input
                SettingsHelper.Validate(mappedSettings);

                // verify settings are correct
                var apiHelper    = new GigyaApiHelper(SettingsHelper, Logger);
                var testResponse = apiHelper.VerifySettings(mappedSettings, plainTextApplicationSecret);
                if (testResponse.GetErrorCode() != 0)
                {
                    var gigyaErrorDetail = testResponse.GetString("errorDetails", string.Empty);
                    var message          = string.Concat("Error: ", testResponse.GetErrorMessage());
                    if (!string.IsNullOrEmpty(gigyaErrorDetail))
                    {
                        message = string.Concat(message, ". ", gigyaErrorDetail);
                    }

                    throw new InvalidOperationException(message);
                }

                context.Add(settings);
                context.SaveChanges();
            }
        }