Ejemplo n.º 1
0
        private void FormValidate(object sender, FormValidationEventArgs e)
        {
            LogHelper.Info <UmbracoFormsEvents>("FormValidate with ReCaptcha Running...");

            var matchingFields = e.Form.AllFields.Where(f => f.FieldType.Name.Contains("GoogleReCaptcha")).ToList();

            if (!matchingFields.Any())
            {
                return;
            }

            var reCaptchaField = matchingFields.FirstOrDefault();

            var httpContext = HttpContext.Current;
            var secretKey   = Umbraco.Forms.Core.Configuration.GetSetting("RecaptchaPrivateKey");

            if (secretKey == "")
            {
                LogHelper.Warn <UmbracoFormsEvents>("ERROR: ReCaptcha v.2 is missing the Secret Key - Please update the '/app_plugins/umbracoforms/umbracoforms.config' to include 'key=\"RecaptchaPrivateKey\"'");
            }
            else
            {
                var reCaptchaResponse = httpContext.Request["g-recaptcha-response"];

                var url = string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", secretKey, reCaptchaResponse);

                var isSuccess  = false;
                var errorCodes = new List <string>();

                using (var client = new WebClient())
                {
                    var response = client.DownloadString(url);

                    var responseParsed = JObject.Parse(response);

                    //Get Success Status
                    JToken sucessToken;
                    var    sucessFound = responseParsed.TryGetValue("success", out sucessToken);
                    if (sucessFound)
                    {
                        isSuccess = sucessToken.Value <bool>();
                    }

                    //Get Error codes
                    JToken errorsToken;
                    var    errorsFound = responseParsed.TryGetValue("error-codes", out errorsToken);
                    if (errorsFound)
                    {
                        var errorsChildren = errorsToken.Children();
                        errorCodes.AddRange(errorsChildren.Select(child => child.Value <string>()));
                    }
                    else
                    {
                        errorCodes.Add("unknown-error");
                    }
                }

                if (isSuccess)
                {
                    return;
                }

                var controller = sender as Controller;

                var compiledErrors = ",";

                foreach (var code in errorCodes)
                {
                    compiledErrors += ", " + code;
                }

                compiledErrors = compiledErrors.Replace(",,", "");

                //Add errors to Form Model
                var errorMsg = string.Format("Recaptcha Verification Failed: {0}", compiledErrors);
                if (reCaptchaField != null)
                {
                    if (controller != null)
                    {
                        controller.ModelState.AddModelError(reCaptchaField.Id.ToString(), errorMsg);
                    }
                }
            }
        }
        private void RecaptchaValidate(object sender, FormValidationEventArgs e)
        {
            LogHelper.Info <UmbracoEvents>("FormValidate with ReCaptcha Running...");

            Field reCaptchaField = e.Form.AllFields.FirstOrDefault(f => f.FieldType.Id == new Guid(EnmFieldTypeId.PerplexRecaptcha.Description()));

            if (reCaptchaField == null)
            {
                return;
            }

            var httpContext = HttpContext.Current;
            var secretKey   = Umbraco.Forms.Core.Configuration.GetSetting("RecaptchaPrivateKey");

            if (string.IsNullOrEmpty(secretKey))
            {
                LogHelper.Warn <UmbracoEvents>("ERROR: ReCaptcha v.2 is missing the Secret Key - Please update the '/app_plugins/umbracoforms/umbracoforms.config' to include 'key=\"RecaptchaPrivateKey\"'");
                return;
            }

            var reCaptchaResponse = httpContext.Request["g-recaptcha-response"];

            var url =
                $"https://www.google.com/recaptcha/api/siteverify?secret={secretKey}&response={reCaptchaResponse}";

            var isSuccess  = false;
            var errorCodes = new List <string>();

            using (var client = new WebClient())
            {
                var response = client.DownloadString(url);

                var responseParsed = JObject.Parse(response);

                //Get Success Status
                JToken sucessToken;
                var    sucessFound = responseParsed.TryGetValue("success", out sucessToken);
                if (sucessFound)
                {
                    isSuccess = sucessToken.Value <bool>();
                }

                //Get Error codes
                JToken errorsToken;
                var    errorsFound = responseParsed.TryGetValue("error-codes", out errorsToken);
                if (errorsFound)
                {
                    var errorsChildren = errorsToken.Children();
                    errorCodes.AddRange(errorsChildren.Select(child => child.Value <string>()));
                }
                else
                {
                    errorCodes.Add("unknown-error");
                }
            }

            if (isSuccess)
            {
                return;
            }

            // DK | 2016-11-04
            // Original code below reads actual error codes from Recaptcha.
            // We should look into this in the future if we may want to display
            // specific errors. For now, we use the configured error message
            // from the field itself or our settings configuration file.
            // Commented out for the time being.

            /*
             * var compiledErrors = ",";
             * foreach (var code in errorCodes)
             * {
             *  //TODO: Use Dictionary Keys to return error message text
             *  compiledErrors += ", " + code;
             * }
             * compiledErrors = compiledErrors.Replace(",,", "");
             * var errorMsg = $"Recaptcha Verification Failed: {compiledErrors}";
             */

            // Add errors to Form Model
            var controller = sender as Controller;

            if (controller == null)
            {
                return;
            }

            // Get configured error message, either from the specific form or otherwise
            // the globally configured one
            string errorMsg = GetSettingValue(
                reCaptchaField,
                nameof(PerplexRecaptcha.ErrorMessage),
                PerplexUmbracoFormsConfig.Get.PerplexRecaptchConfig.ErrorMessage
                );

            controller.ModelState.AddModelError(reCaptchaField.Id.ToString(), errorMsg);
        }