Esempio n. 1
0
        public string CreateNonce(IUser user, TimeSpan delay)
        {
            var challengeToken = new XElement("n", new XAttribute("un", user.UserName), new XAttribute("utc", _clock.UtcNow.ToUniversalTime().Add(delay).ToString(CultureInfo.InvariantCulture))).ToString();
            var data           = Encoding.UTF8.GetBytes(challengeToken);

            return(Convert.ToBase64String(_encryptionService.Encode(data)));
        }
        public string CreateNonce(int contentItemId, string signal)
        {
            var challengeToken = new XElement("n", new XAttribute("c", contentItemId), new XAttribute("n", signal)).ToString();
            var data           = Encoding.UTF8.GetBytes(challengeToken);

            return(Convert.ToBase64String(_encryptionService.Encode(data)));
        }
        private void lazyLoadHandlers(SocrataSettingsPart part)
        {
            //decrypt stored password on read
            part.PasswordField.Getter(() => {
                try
                {
                    var encryptedPassword = part.Retrieve(x => x.Password);
                    return(String.IsNullOrWhiteSpace(encryptedPassword)
                        ? String.Empty
                        : Encoding.UTF8.GetString(_encryptionService.Decode(Convert.FromBase64String(encryptedPassword))));
                }
                catch
                {
                    Logger.Error("The Socrata password could not be decrypted. It might be corrupted, try to reset it.");
                    return(null);
                }
            });

            // encrypt plaintext password on write
            part.PasswordField.Setter(value => {
                var encryptedPassword = String.IsNullOrWhiteSpace(value)
                    ? String.Empty
                    : Convert.ToBase64String(_encryptionService.Encode(Encoding.UTF8.GetBytes(value)));

                part.Store(x => x.Password, encryptedPassword);
            });
        }
Esempio n. 4
0
        public virtual APIResult <FidelityCustomer> CreateFidelityAccount(FidelityUserPart fidelityPart, string username, string email, string campaignId)
        {
            if (fidelityPart != null && !String.IsNullOrWhiteSpace(username))
            {
                FidelityCustomer customer = new FidelityCustomer(email, username, Membership.GeneratePassword(12, 4));

                APIResult <FidelityCustomer> creationRequest = _sendService.SendCustomerRegistration(settingsPart, customer, campaignId);

                if (creationRequest.success)
                {
                    fidelityPart.FidelityUsername = customer.Username;

                    fidelityPart.FidelityPassword = Convert.ToBase64String(_encryptionService.Encode(Encoding.UTF8.GetBytes(customer.Password)));
                    if (!string.IsNullOrWhiteSpace(customer.Id))
                    {
                        fidelityPart.CustomerId = customer.Id;
                    }
                }
                return(creationRequest);
            }
            else
            {
                return new APIResult <FidelityCustomer> {
                           success = false, data = null, message = "The user is not configured to use " + GetProviderName()
                }
            };
        }
Esempio n. 5
0
        protected override DriverResult Editor(FidelitySiteSettingsPart part, IUpdateModel updater, dynamic shapeHelper)
        {
            string oldPwd = part.MerchantPwd;
            FidelitySiteSettingsViewModel fidelityVM = new FidelitySiteSettingsViewModel();

            if (updater.TryUpdateModel(fidelityVM, Prefix, null, null))
            {
                if (!String.IsNullOrWhiteSpace(fidelityVM.ApiURL))   // trattandosi di settings aggiorno solo se un parametro obbligatorio è presente, altrimenti non deve aggiornare. L'effetto altrimento sarebbe dell'azzeramento dei settings per la fidelity
                {
                    if (!String.IsNullOrEmpty(fidelityVM.MerchantPwd))
                    {
                        string encryptedPwd = Convert.ToBase64String(_encryptionService.Encode(Encoding.UTF8.GetBytes(fidelityVM.MerchantPwd)));

                        if (encryptedPwd != oldPwd)
                        {
                            part.MerchantSessionId = "";
                        }

                        part.MerchantPwd = encryptedPwd;
                    }
                    else
                    {
                        part.MerchantPwd = oldPwd;
                    }

                    part.ApiURL           = fidelityVM.ApiURL;
                    part.DeveloperKey     = fidelityVM.DeveloperKey;
                    part.MerchantUsername = fidelityVM.MerchantUsername;
                }
                part.RegisterOnLogin = fidelityVM.RegisterOnLogin;
            }

            return(Editor(part, shapeHelper));
        }
Esempio n. 6
0
 public static string EncodePassword(string value, IEncryptionService encryptionService)
 {
     return
         string.IsNullOrWhiteSpace(value) ?
         string.Empty :
         Convert.ToBase64String(encryptionService.Encode(Encoding.UTF8.GetBytes(value)));
 }
Esempio n. 7
0
        public void GenerateNewCredentials(ApiCredentialsPart part)
        {
            // we use base64 to prevent possible encoding issues on transmission
            var key = Convert.ToBase64String(
                Encoding.UTF8.GetBytes(BearerTokenHelpers.RandomString(24)),
                Base64FormattingOptions.None);

            // test that we haven't used this already. It's random but better safe than sorry.
            while (GetPartByKey(key) != null)
            {
                key = Convert.ToBase64String(
                    Encoding.UTF8.GetBytes(BearerTokenHelpers.RandomString(24)),
                    Base64FormattingOptions.None);
            }
            part.ApiKey = key;
            // encryption and hashing of the secret
            var secret = Convert.ToBase64String(
                Encoding.UTF8.GetBytes(BearerTokenHelpers.RandomString()),
                Base64FormattingOptions.None);

            // save an encrypted secret so we can display it to authorized users
            part.ApiSecret = Convert.ToBase64String(
                _encryptionService.Encode(
                    Encoding.UTF8.GetBytes(secret)));
            // save an hashed secret for validation when signing in
            part.HashAlgorithm = BearerTokenHelpers.PBKDF2;
            BearerTokenHelpers.SetSecretHashed(part, secret);

            part.CreatedUtc = _clock.UtcNow;
        }
Esempio n. 8
0
        public void SetSettings(PaypalSettings Settings)
        {
            var settingsPart = Services.WorkContext.CurrentSite.As <OShopPaypalSettingsPart>();

            settingsPart.UseSandbox   = Settings.UseSandbox;
            settingsPart.ClientId     = Settings.ClientId;
            settingsPart.ClientSecret = Convert.ToBase64String(_encryptionService.Encode(Encoding.UTF8.GetBytes(Settings.ClientSecret)));
        }
Esempio n. 9
0
 public static string Ciphertext(this IEncryptionService service, string cleartext, Encoding encodeing = null)
 {
     if (encodeing == null)
     {
         encodeing = UTF8Encoding.Default;
     }
     return(Convert.ToBase64String(service.Encode(encodeing.GetBytes(cleartext))));
 }
Esempio n. 10
0
        private string createHash(int userId, int appId, TimeSpan delay)
        {
            var challengeToken = new XElement("n",
                                              new XAttribute("ui", userId),
                                              new XAttribute("ai", appId),
                                              new XAttribute("utc", _clock.UtcNow.ToUniversalTime().Add(delay).ToString(CultureInfo.InvariantCulture))).ToString();
            var data = Encoding.UTF8.GetBytes(challengeToken);

            return(Convert.ToBase64String(_encryptionService.Encode(data)));
        }
Esempio n. 11
0
        public string SerializeProviderUserId(string providerName, string providerUserId)
        {
            Argument.ThrowIfNullOrEmpty(providerName, "providerName");
            Argument.ThrowIfNullOrEmpty(providerUserId, "providerUserId");

            var protectedBytes = ToByteArray(new SerializedProvider {
                ProviderName = providerName, ProviderUserId = providerUserId
            });

            return(Convert.ToBase64String(_encryptionService.Encode(protectedBytes)));
        }
        public void SaveUserIdamDataToCookie(IEnumerable <Claim> claims, HttpContext context)
        {
            // store claims into a secure cookie
            var jwtToken = _jwtTokenService.GenerateJwtToken(claims, Settings.JwtTokenSecurityKey);

            var encodedJwtToken = _encryptionService.Encode(jwtToken);

            var userDataCookie = new CookieHelper(Settings.UserDataCookieName, context);

            userDataCookie.SetValue(Settings.UserDataCookieKey, encodedJwtToken);
            userDataCookie.Save();
        }
        protected override DriverResult Editor(LoyalzooUserPart part, IUpdateModel updater, dynamic shapeHelper)
        {
            if (currentControllerAction == CONTROLLER_ACTION)
            {
                return(null);                                              // nulla deve essere mostrato in fase di registrazione
            }
            string oldPwd = part.LoyalzooPassword;
            string oldId  = part.CustomerSessionId;

            LoyalzooUserSettingsViewModel userVM = new LoyalzooUserSettingsViewModel();

            if (updater.TryUpdateModel(userVM, Prefix, null, null))
            {
                part.LoyalzooUsername  = userVM.LoyalzooUsername;
                part.CustomerSessionId = userVM.CustomerSessionId;

                if (!String.IsNullOrWhiteSpace(userVM.LoyalzooPassword))
                {
                    string encryptedPwd = Convert.ToBase64String(_encryptionService.Encode(Encoding.UTF8.GetBytes(userVM.LoyalzooPassword)));

                    if (encryptedPwd != oldPwd && userVM.CustomerSessionId == oldId)
                    {
                        part.CustomerSessionId = "";
                    }

                    part.LoyalzooPassword = encryptedPwd;
                }
                else
                {
                    part.LoyalzooPassword = oldPwd;
                }

                // Se l'utente ha tentato di cancellare tutte le credenziali cancello anche la password
                if (string.IsNullOrWhiteSpace(userVM.LoyalzooUsername) && string.IsNullOrWhiteSpace(userVM.CustomerSessionId))
                {
                    part.LoyalzooPassword = "";
                }
            }

            return(Editor(part, shapeHelper));
        }
Esempio n. 14
0
 private void SetPasswordEncrypted(UserPart userPart, string password)
 {
     userPart.Password       = Convert.ToBase64String(_encryptionService.Encode(Encoding.UTF8.GetBytes(password)));
     userPart.PasswordSalt   = null;
     userPart.PasswordFormat = MembershipPasswordFormat.Encrypted;
 }
Esempio n. 15
0
        void LazyLoadHandlers(LoadContentContext context, TwilioSettingsPart part)
        {
            part.AuthTokenField.Getter(() => {
                try {
                    var encryptedAuthToken = part.Retrieve(x => x.AuthToken);
                    return(String.IsNullOrWhiteSpace(encryptedAuthToken) ? String.Empty : Encoding.UTF8.GetString(_encryptionService.Decode(Convert.FromBase64String(encryptedAuthToken))));
                }
                catch {
                    Logger.Error("The Twilio authtoken password could not be decrypted. It might be corrupted, try to reset it.");
                    return(null);
                }
            });

            part.AuthTokenField.Setter(value => {
                var encryptedAuthToken = String.IsNullOrWhiteSpace(value) ? String.Empty : Convert.ToBase64String(_encryptionService.Encode(Encoding.UTF8.GetBytes(value)));
                part.Store(x => x.AuthToken, encryptedAuthToken);
            });
        }
Esempio n. 16
0
        private void LazyLoadHandlers(LoadContentContext context, IMAPSettingPart part)
        {
            part.PasswordField.Getter(() =>
            {
                try
                {
                    var encryptedPassword = part.Retrieve(x => x.Password);
                    return(String.IsNullOrWhiteSpace(encryptedPassword) ? String.Empty : Encoding.UTF8.GetString(_encryptionService.Decode(Convert.FromBase64String(encryptedPassword))));
                }
                catch
                {
                    Logger.Error("The email password could not be decrypted. It might be corrupted, try to reset it.");
                    return(null);
                }
            });

            part.PasswordField.Setter(value =>
            {
                var encryptedPassword = String.IsNullOrWhiteSpace(value) ? String.Empty : Convert.ToBase64String(_encryptionService.Encode(Encoding.UTF8.GetBytes(value)));
                part.Store(x => x.Password, encryptedPassword);
            });
        }
        void LazyLoadHandlers(LoadContentContext context, AdSettingsPart part)
        {
            part.PasswordField.Getter(() =>
            {
                try
                {
                    return(string.IsNullOrWhiteSpace(part.Record.Password) ? string.Empty : Encoding.UTF8.GetString(_encryptionService.Decode(Convert.FromBase64String(part.Record.Password))));
                }
                catch
                {
                    Logger.Error("The Ad Settings password could not be decrypted. It might be corrupted, try to reset it.");
                    return(null);
                }
            });

            part.PasswordField.Setter(value => part.Record.Password = string.IsNullOrWhiteSpace(value) ? string.Empty : Convert.ToBase64String(_encryptionService.Encode(Encoding.UTF8.GetBytes(value))));
        }
        public APIResult CreateLoyalzooAccount(LoyalzooUserPart loyalzooPart, string username, string email)
        {
            try
            {
                APIResult result = new APIResult();

                if (loyalzooPart != null && !String.IsNullOrWhiteSpace(username) && !String.IsNullOrWhiteSpace(email))
                {
                    if (String.IsNullOrWhiteSpace(loyalzooPart.LoyalzooUsername) && String.IsNullOrWhiteSpace(loyalzooPart.LoyalzooPassword) && String.IsNullOrWhiteSpace(loyalzooPart.CustomerSessionId))
                    {
                        ConfigEnv configData = GetConfigData();

                        CDataCustomer customerData = new CDataCustomer();
                        customerData.first_name = username;
                        customerData.email      = email;
                        customerData.username   = username;
                        customerData.password   = Membership.GeneratePassword(12, 4);

                        ILoyalzooCustomer customer        = new Customer();
                        CResultCreate     creationRequest = customer.Create(configData, customerData);

                        if (creationRequest.success)
                        {
                            loyalzooPart.LoyalzooUsername  = creationRequest.response.username;
                            loyalzooPart.CustomerSessionId = creationRequest.response.session_id;
                            loyalzooPart.LoyalzooPassword  = Convert.ToBase64String(_encryptionService.Encode(Encoding.UTF8.GetBytes(customerData.password)));

                            result.success = true;
                            result.data    = creationRequest.response;
                            result.message = "";
                        }
                        else
                        {
                            result.success = false;
                            result.message = creationRequest.Errore.response;
                            result.data    = null;
                        }
                    }
                    else
                    {
                        return new APIResult {
                                   success = false, data = null, message = "There is already some Loyalzoo data associated to the user. If you want to register a new account, delete the existing Loyalzoo data and then call this method again (any previous data associated to the user will be lost)."
                        }
                    };
                }
                else
                {
                    return new APIResult {
                               success = false, data = null, message = "The user is not configured to use Loyalzoo."
                    }
                };

                return(result);
            }
            catch (Exception e)
            {
                APIResult exceptionData = new APIResult();

                exceptionData.success = false;
                exceptionData.message = e.Message;
                exceptionData.data    = null;

                return(exceptionData);
            }
        }
Esempio n. 19
0
        public MarkdownRepoPartHandler(
            IMarkdownContentItemManager markdownContentItemManager,
            IRepository <MarkdownRepoPartRecord> repository,
            IScheduledTaskManager scheduledTaskManager,
            IClock clock,
            IContentManager contentManager,
            IEncryptionService encryptionService)
        {
            Filters.Add(StorageFilter.For(repository));

            OnActivated <MarkdownRepoPart>((context, part) =>
            {
                part.AccessTokenField.Loader(() =>
                {
                    return(string.IsNullOrEmpty(part.EncodedAccessToken)
                        ? ""
                        : Encoding.UTF8.GetString(encryptionService.Decode(Convert.FromBase64String(part.EncodedAccessToken))));
                });

                part.AccessTokenField.Setter((value) =>
                {
                    part.EncodedAccessToken = string.IsNullOrEmpty(value)
                        ? ""
                        : Convert.ToBase64String(encryptionService.Encode(Encoding.UTF8.GetBytes(value)));

                    return(value);
                });

                part.PasswordField.Loader(() =>
                {
                    return(string.IsNullOrEmpty(part.EncodedPassword)
                        ? ""
                        : Encoding.UTF8.GetString(encryptionService.Decode(Convert.FromBase64String(part.EncodedPassword))));
                });

                part.PasswordField.Setter((value) =>
                {
                    part.EncodedPassword = string.IsNullOrEmpty(value)
                        ? ""
                        : Convert.ToBase64String(encryptionService.Encode(Encoding.UTF8.GetBytes(value)));

                    return(value);
                });
            });

            OnRemoved <MarkdownRepoPart>((ctx, part) =>
            {
                scheduledTaskManager.DeleteTasks(part.ContentItem);

                if (part.DeleteMarkdownPagesOnRemoving == true)
                {
                    markdownContentItemManager.DeleteAll(part);
                }
                // Since the repo is deleted we doesn't want to prevent the deletion of the markdown pages.
                else
                {
                    var correspondingMarkdownPages = contentManager
                                                     .Query(part.ContentType)
                                                     .Where <MarkdownPagePartRecord>(record => record.MarkdownRepoId == part.ContentItem.Id)
                                                     .List();

                    foreach (var correspondingMarkdownPage in correspondingMarkdownPages)
                    {
                        correspondingMarkdownPage.As <MarkdownPagePart>().DeletionAllowed = true;
                    }
                }
            });

            OnPublished <MarkdownRepoPart>((ctx, part) =>
            {
                if (ctx.PreviousItemVersionRecord != null)
                {
                    scheduledTaskManager.DeleteTasks(part.ContentItem);
                }

                scheduledTaskManager
                .CreateTask(
                    TaskNameHelper.GetMarkdownContentUpdaterTaskName(part.ContentItem),
                    clock.UtcNow.AddMinutes(1),
                    part.ContentItem);
            });
        }
Esempio n. 20
0
 private void SetPasswordEncrypted(UserPartRecord partRecord, string password)
 {
     partRecord.Password     = Convert.ToBase64String(_encryptionService.Encode(Encoding.UTF8.GetBytes(password)));
     partRecord.PasswordSalt = null;
 }
Esempio n. 21
0
        protected override DriverResult Editor(ContentPart part, Fields.SecureFileField field, IUpdateModel updater, dynamic shapeHelper)
        {
            WorkContext wc   = _workContextAccessor.GetContext();
            var         file = wc.HttpContext.Request.Files["FileField-" + field.Name];

            // if the model could not be bound, don't try to validate its properties
            if (updater.TryUpdateModel(field, GetPrefix(field, part), null, null))
            {
                var settings = field.PartFieldDefinition.Settings.GetModel <SecureFileFieldSettings>();

                var extensions = String.IsNullOrWhiteSpace(settings.AllowedExtensions)
                        ? new string[0]
                        : settings.AllowedExtensions.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                try {
                    if (file != null && file.ContentLength > 0)
                    {
                        string fname = Path.GetFileName(file.FileName);
                        if (settings.GenerateFileName)
                        {
                            var extension = Path.GetExtension(file.FileName);
                            fname = Guid.NewGuid().ToString("n") + extension;
                        }
                        if (extensions.Any() && fname != null && !extensions.Any(x => fname.EndsWith(x, StringComparison.OrdinalIgnoreCase)))
                        {
                            updater.AddModelError("Url", T("The field {0} must have one of these extensions: {1}", field.DisplayName.CamelFriendly(), settings.AllowedExtensions));
                            return(Editor(part, field, shapeHelper));
                        }

                        if (settings.Required && String.IsNullOrWhiteSpace(fname))
                        {
                            updater.AddModelError("Url", T("The field {0} is mandatory", field.DisplayName.CamelFriendly()));
                            return(Editor(part, field, shapeHelper));
                        }

                        DateTime upload = DateTime.UtcNow;
                        field.Upload = upload;
                        field.Url    = fname;
                        IStorageProvider provider;

                        if (!string.IsNullOrEmpty(settings.SecureBlobAccountName))
                        {
                            provider = new SecureAzureBlobStorageProvider(settings.SecureBlobAccountName, settings.SecureSharedKey,
                                                                          settings.SecureBlobEndpoint, true, settings.SecureDirectoryName);
                        }
                        else
                        {
                            string url       = settings.SecureDirectoryName;
                            string subfolder = _tokenizer.Replace(settings.CustomSubfolder, new Dictionary <string, object> {
                                { "Content", part.ContentItem }
                            });

                            if (!string.IsNullOrWhiteSpace(subfolder))
                            {
                                field.Subfolder = subfolder;
                                url             = Path.Combine(url, subfolder);
                                if (!Directory.Exists(url))
                                {
                                    Directory.CreateDirectory(url);
                                }
                            }

                            provider = new SecureFileStorageProvider(url);
                        }

                        int    length = (int)file.ContentLength;
                        byte[] buffer = new byte[length];
                        using (Stream stream = file.InputStream) {
                            stream.Read(buffer, 0, length);
                        }

                        if (settings.EncryptFile)
                        {
                            buffer = _encryptionService.Encode(buffer);
                        }

                        provider.Insert(fname, buffer, file.ContentType, length, true);
                    }
                } catch (Exception) {
                    throw;
                }
            }

            return(Editor(part, field, shapeHelper));
        }
Esempio n. 22
0
 public static string Encrypt(this IEncryptionService service, string value)
 {
     return(Convert.ToBase64String(service.Encode(Encoding.UTF8.GetBytes(value))));
 }
 public static string SetPasswordEncrypted(this BitbucketRepositoryDataRecord settings, IEncryptionService encryptionService, string plainPassword)
 {
     if (plainPassword == null) plainPassword = string.Empty;
     settings.Password = Convert.ToBase64String(encryptionService.Encode(Encoding.UTF8.GetBytes(plainPassword)));
     return settings.Password;
 }
        void LazyLoadHandlers(LoadContentContext context, SmtpSettingsPart part)
        {
            part.PasswordField.Getter(() => {
                try {
                    var encryptedPassword = part.Retrieve(x => x.Password);
                    return(String.IsNullOrWhiteSpace(encryptedPassword) ? String.Empty : Encoding.UTF8.GetString(_encryptionService.Decode(Convert.FromBase64String(encryptedPassword))));
                }
                catch {
                    Logger.Error("The email password could not be decrypted. It might be corrupted, try to reset it.");
                    return(null);
                }
            });

            part.PasswordField.Setter(value => {
                var encryptedPassword = String.IsNullOrWhiteSpace(value) ? String.Empty : Convert.ToBase64String(_encryptionService.Encode(Encoding.UTF8.GetBytes(value)));
                part.Store(x => x.Password, encryptedPassword);
            });

            part.AddressPlaceholderField.Loader(value => (string)((dynamic)ConfigurationManager.GetSection("system.net/mailSettings/smtp")).From);
        }
Esempio n. 25
0
        public string CryptApiKey(string apikey)
        {
            var settings = _orchardServices.WorkContext.CurrentSite.As <MailchimpSiteSettings>();

            return(Convert.ToBase64String(_encryptionService.Encode(Encoding.UTF8.GetBytes(apikey))));
        }