public bool validateRecaptcha(string response)
        {
            bool valid = false;
            //Request to Google Server
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create($"https://www.google.com/recaptcha/api/siteverify?secret={_secretKey}&response={response}");

            try
            {
                //Google recaptcha Responce
                using (WebResponse wResponse = req.GetResponse())
                {
                    using (StreamReader readStream = new StreamReader(wResponse.GetResponseStream()))
                    {
                        string jsonResponse = readStream.ReadToEnd();

                        JavaScriptSerializer js   = new JavaScriptSerializer();
                        RecaptchaResponse    data = js.Deserialize <RecaptchaResponse>(jsonResponse);// Deserialize Json

                        valid = Convert.ToBoolean(data.success);
                    }
                }

                return(valid);
            }
            catch (WebException ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// The validate.
        /// </summary>
        public void Validate()
        {
            if (this.skipRecaptcha)
            {
                this.recaptchaResponse = RecaptchaResponse.Valid;
            }
            else
            {
                var validator = new RecaptchaValidator
                {
                    PrivateKey = this.privateKey, RemoteIP = Utils.GetClientIP()
                };
                if (String.IsNullOrEmpty(this.RecaptchaChallengeValue) &&
                    String.IsNullOrEmpty(this.RecaptchaResponseValue))
                {
                    validator.Challenge = this.Context.Request.Form[RecaptchaChallengeField];
                    validator.Response  = this.Context.Request.Form[RecaptchaResponseField];
                }
                else
                {
                    validator.Challenge = this.RecaptchaChallengeValue;
                    validator.Response  = this.RecaptchaResponseValue;
                }

                this.recaptchaResponse = validator.Validate();
            }
        }
Exemple #3
0
        private void CheckReCaptcha(RecaptchaResponse recaptchaResponse, StringBuilder reasonForModeration)
        {
            if (!recaptchaResponse.success)
            {
                reasonForModeration.AppendLine("reCAPTCHA success is false");
            }

            if (recaptchaResponse.score < _settings.ReCaptchaMinimumScore)
            {
                reasonForModeration.AppendLine(
                    $"reCAPTCHA score < minimum required score ({recaptchaResponse.score} < {_settings.ReCaptchaMinimumScore})");
            }

            if (string.Compare(recaptchaResponse.hostname, _settings.ReCaptchaHostname,
                               StringComparison.InvariantCultureIgnoreCase) != 0)
            {
                reasonForModeration.AppendLine(
                    $"reCAPTCHA hostname != expected hostname ('{recaptchaResponse.hostname}' != '{_settings.ReCaptchaHostname}')");
            }

            if (string.Compare(recaptchaResponse.action, _settings.ReCaptchaAction,
                               StringComparison.InvariantCultureIgnoreCase) != 0)
            {
                reasonForModeration.AppendLine(
                    $"reCAPTCHA action != expected action ('{recaptchaResponse.action}' != '{_settings.ReCaptchaAction}')");
            }
        }
        public void Validate()
        {
            if (skipRecaptcha)
            {
                recaptchaResponse = RecaptchaResponse.Valid;
            }
            else
            {
                RecaptchaValidator validator = new RecaptchaValidator();
                validator.PrivateKey = privateKey;
                validator.RemoteIP   = Page.Request.UserHostAddress;
                if (String.IsNullOrEmpty(RecaptchaChallengeValue) && String.IsNullOrEmpty(RecaptchaResponseValue))
                {
                    validator.Challenge = Context.Request.Form[RECAPTCHA_CHALLENGE_FIELD];
                    validator.Response  = Context.Request.Form[RECAPTCHA_RESPONSE_FIELD];
                }
                else
                {
                    validator.Challenge = RecaptchaChallengeValue;
                    validator.Response  = RecaptchaResponseValue;
                }

                recaptchaResponse = validator.Validate();
            }
        }
Exemple #5
0
        private void TasksProccesing()
        {
            if (ReferenceEquals(_tasks, null) || _tasks.Count.Equals(0))
            {
                return;
            }

            try
            {
                foreach (var item in _tasks.Where(el => el.Status.Equals(RuCaptchaTaskStatus.NotReady)))
                {
                    var rr = (HttpWebRequest)WebRequest.Create(
                        $"http://rucaptcha.com/res.php?key={CaptchaApiToken}&action=get&id={item.RequestId}&json=1");

                    using (var r = (HttpWebResponse)rr.GetResponse())
                    {
                        using (var s = r.GetResponseStream())
                        {
                            using (var sr = new StreamReader(s))
                            {
                                RecaptchaResponse = sr.ReadToEnd();
                            }

                            if (RecaptchaResponse.Equals(CaptchaIsNotReady))
                            {
                                _logger.Info("Response from Recaptcha not ready... sleepping....");
                                InvokeOnRecaptchaV2TaskCallback(item);
                            }
                            else if (RecaptchaResponse.Equals(CaptchaIsUnsolvable))
                            {
                                _logger.Error(
                                    "Response from Recaptcha: captcha cannot be solved, check sita settings....");
                                InvokeOnRecaptchaV2TaskCallback(item);
                                item.Status = RuCaptchaTaskStatus.Unsolvable;
                            }
                            else
                            {
                                var trdto = JsonConvert.DeserializeObject <RucaptchaTaskResponseDto>(RecaptchaResponse);

                                if (!trdto.Data.Equals(CaptchaIsNotReady))
                                {
                                    item.CaptchaSolution = trdto.Data;
                                    InvokeOnRecaptchaV2TaskCallback(item);
                                }
                                else
                                {
                                    InvokeOnRecaptchaV2TaskCallback(item);
                                    _logger.Info("Response from Recaptcha not ready... sleepping....");
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception exc)
            {
                _logger.Error("While trying to check task status in RuCaptcha, exception occured!");
                _logger.Exception(exc);
            }
        }
Exemple #6
0
        /// <summary>
        /// The validate.
        /// </summary>
        public void Validate()
        {
            if (this.skipRecaptcha)
            {
                this.recaptchaResponse = RecaptchaResponse.Valid;
            }
            else
            {
                var validator = new RecaptchaValidator
                {
                    PrivateKey = this.privateKey,
                    RemoteIP   = Utils.GetClientIP()
                };
                if (this.RecaptchaResponseValue == null)
                {
                    validator.Response = this.Context.Request.Form[RecaptchaResponseField];
                }
                else
                {
                    validator.Response = this.RecaptchaResponseValue;
                }

                this.recaptchaResponse = validator.Validate();
            }
        }
Exemple #7
0
        public async Task <IActionResult> OnPostUnregisterAsync()
        {
            ReferencedCalendarItem = await _repository.GetDocument(CalendarItemId);

            UseCaptcha = !User.Identity.IsAuthenticated && null != ReferencedCalendarItem && ReferencedCalendarItem.PublicListing;
            if (UseCaptcha)
            {
                RecaptchaResponse captchaValid = await _recaptcha.Validate(Request);

                if (!captchaValid.success)
                {
                    ModelState.AddModelError("reCaptcha", "Bitte das reCaptcha bestätigen.");
                }
            }
            if (!ModelState.IsValid)
            {
                ViewData["Message"] = "Schiefgegangen";
                return(Page());
            }
            Member        memberToUnregister;
            List <Member> members;

            if (null == ReferencedCalendarItem)
            {
                return(new NotFoundResult());
            }
            members            = (ReferencedCalendarItem.Members != null) ? new List <Member>(ReferencedCalendarItem.Members) : new List <Member>();
            memberToUnregister = members.Find(m => m.EMail == NewMember.EMail && m.Name == NewMember.Name);
            if (null == memberToUnregister)
            {
                ModelState.AddModelError("EMail", "E-Mail und Name stimmen mit keiner Anmeldung überein.");
                return(Page());
            }
            if (ReferencedCalendarItem.RegistrationKeyRequired)
            {
                RegistrationKey checkKey = ReferencedCalendarItem.RegistrationKeys.FirstOrDefault(r => r.Key == NewMember.RegistrationKey);
                if (null == checkKey)
                {
                    ModelState.AddModelError("RegistrationKey", "Der angegebene Registrierungsschlüssel ist nicht zulässig.");
                    return(Page());
                }
            }
            if (ModelState.IsValid)
            {
                members.RemoveAll(c => c.UniqueId == memberToUnregister.UniqueId);
                ReferencedCalendarItem.Members = members.OrderBy(m => m.RegistrationDate).ToArray();
                await _repository.UpsertDocument(ReferencedCalendarItem);

                ViewData["Message"] = "Abgemeldet";
                return(RedirectToPage("Index", new { permalink = ReferencedCalendarItem.UrlTitle, message = "Anmeldung gelöscht." }));
            }
            else
            {
                ViewData["Message"] = "Schiefgegangen";
                return(Page());
            }
        }
Exemple #8
0
        public override bool Equals(object obj)
        {
            RecaptchaResponse other = (RecaptchaResponse)obj;

            if (other == null)
            {
                return(false);
            }

            return(other.IsValid == IsValid && other.ErrorCode == ErrorCode);
        }
        public static IRecaptchaService Create(bool success)
        {
            var reCaptchaResponse = new RecaptchaResponse {
                success = success
            };

            var mockReCaptcha = new Mock <IRecaptchaService>();

            mockReCaptcha.Setup(m => m.Validate(It.IsAny <HttpRequest>(), It.IsAny <bool>())).ReturnsAsync(reCaptchaResponse);
            var reCaptcha = mockReCaptcha.Object;

            return(reCaptcha);
        }
Exemple #10
0
        protected bool IsValidRecaptcha(string recaptchaResponse)
        {
            string url = string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", Config.GOOGLE_CAPTCHA_SECRET, recaptchaResponse);

            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
                using (HttpResponseMessage response = client.PostAsync(url, null).Result)
                {
                    RecaptchaResponse result = JsonConvert.DeserializeObject <RecaptchaResponse>(response.Content.ReadAsStringAsync().Result);
                    return(result != null && result.Success);
                }
            }
        }
Exemple #11
0
        protected bool IsValidRecaptcha(string recaptchaResponse)
        {
            string url = $"https://www.google.com/recaptcha/api/siteverify?secret={Startup.Configuration.GetSection("RecaptchaSecret").Get<string>()}&response={recaptchaResponse}";

            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
                using (HttpResponseMessage response = client.PostAsync(url, null).Result)
                {
                    RecaptchaResponse result = JsonConvert.DeserializeObject <RecaptchaResponse>(response.Content.ReadAsStringAsync().Result);
                    return(result != null && result.Success);
                }
            }
        }
        public static bool Validate(HttpContextBase context)
        {
            var request = context.Request;

            var validator = new RecaptchaValidator
            {
                PrivateKey = ConfigurationManager.AppSettings["ReCaptchaPrivateKey"],
                RemoteIP   = request.UserHostAddress,
                Challenge  = request.Form[ChallengeFieldKey],
                Response   = request.Form[ResponseFieldKey]
            };
            RecaptchaResponse response = validator.Validate();

            return(response.IsValid);
        }
Exemple #13
0
        public async Task <IActionResult> OnPostAsync()
        {
            ReferencedCalendarItem = await _repository.GetDocument(CalendarItemId);

            UseCaptcha = !User.Identity.IsAuthenticated && null != ReferencedCalendarItem && ReferencedCalendarItem.PublicListing;
            if (UseCaptcha)
            {
                RecaptchaResponse captchaValid = await _recaptcha.Validate(Request, false);

                if (!captchaValid.success)
                {
                    ModelState.AddModelError("reCaptcha", "Bitte das reCaptcha bestätigen.");
                }
            }
            if (ModelState.IsValid)
            {
                if (null == ReferencedCalendarItem)
                {
                    return(new NotFoundResult());
                }
                if (ReferencedCalendarItem.RegistrationKeyRequired && !User.IsInAnyRole(KnownRoles.CalendarCoordinatorRoles))
                {
                    RegistrationKey checkKey = ReferencedCalendarItem.RegistrationKeys.FirstOrDefault(r => r.Key == NewMember.RegistrationKey);
                    if (null == checkKey)
                    {
                        ModelState.AddModelError("RegistrationKey", "Der angegebene Registrierungsschlüssel ist nicht zulässig.");
                        return(Page());
                    }
                }
                List <Member> members = (ReferencedCalendarItem.Members != null) ? new List <Member>(ReferencedCalendarItem.Members) : new List <Member>();
                members.RemoveAll(c => c.UniqueId == NewMember.UniqueId);
                members.Add(NewMember);
                ReferencedCalendarItem.Members = members.OrderBy(m => m.RegistrationDate).ToArray();
                if (ReferencedCalendarItem.GetRegisteredMembersCount() > ReferencedCalendarItem.MaxRegistrationsCount && !User.IsInAnyRole(KnownRoles.CalendarCoordinatorRoles))
                {
                    ModelState.AddModelError("RegistrationCount", "Die Anzahl Anmeldungen überschreitet die maximale Teilnehmeranzahl.");
                    return(Page());
                }
                await _repository.UpsertDocument(ReferencedCalendarItem);

                return(RedirectToPage("Index", new { permalink = ReferencedCalendarItem.UrlTitle, message = "Anmeldung erfolgt." }));
            }
            else
            {
                return(Page());
            }
        }
        private async Task <RecaptchaResponse> GetResponseAsync(String token)
        {
            HttpClient            client        = new HttpClient();
            FormUrlEncodedContent requestParams = this.GetParams(token);

            HttpResponseMessage response = await client.PostAsync(_endpoint, requestParams);

            String responseString = await response.Content.ReadAsStringAsync();

            using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(responseString)))
            {
                DataContractJsonSerializer serializer        = new DataContractJsonSerializer(typeof(RecaptchaResponse));
                RecaptchaResponse          recaptchaResponse = (RecaptchaResponse)serializer.ReadObject(stream);

                return(recaptchaResponse);
            }
        }
Exemple #15
0
        public async Task <DefaultCommandResponse> Handle(CheckClosedCompetitionRegistrationsCommand command)
        {
            this._unitOfWork.Begin();
            this._registrationUnitOfWork.Begin();

            RecaptchaResponse recaptchaResponse = null;

            try
            {
                DateTime end   = DateTime.UtcNow;
                DateTime start = end.AddDays(-2);
                var      closedCompetitions = await this._competitionRepository.GetClosedOnlineCompetitions(start, end);

                foreach (var competition in closedCompetitions)
                {
                    var summary = await this._competitionRegistrationSummaryRepository.GetByCompetition(competition.ID);

                    if (summary == null)
                    {
                        List <CompetitionRegistration> registrations = await this._competitionRegistrationRepository.GetAll(competition.ID);

                        await this._registrationEmailManager.SendSummaryEmail(registrations, competition);

                        summary = new CompetitionRegistrationSummary();
                        summary.CompetitionID   = competition.ID;
                        summary.SummarySent     = true;
                        summary.SummarySentDate = DateTime.UtcNow;

                        await this._competitionRegistrationSummaryRepository.Save(summary);
                    }
                }

                this._unitOfWork.SoftCommit();
                this._registrationUnitOfWork.SoftCommit();

                //await this._registrationEmailManager.SendConfirmationEmails(registration, this._competition);
                return(DefaultCommandResponse.Create(new ValidationResult()));
            }
            catch (Exception e)
            {
                this._unitOfWork.Rollback();
                this._registrationUnitOfWork.Rollback();
                this._logger.LogError("Error", e);
                throw;
            }
        }
Exemple #16
0
        public async Task <IActionResult> OnPostAsync()
        {
            RecaptchaResponse captchaValid = await _recaptcha.Validate(Request, false);

            if (!captchaValid.success)
            {
                ModelState.AddModelError("reCaptcha", "Bitte das reCaptcha bestätigen.");
            }
            if (ModelState.IsValid)
            {
                return(Page());
            }
            else
            {
                ViewData["Message"] = "Schiefgegangen";
                return(Page());
            }
        }
Exemple #17
0
        public async Task <bool> ValidateToken(string token)
        {
            HttpRequestMessage message = new HttpRequestMessage(HttpMethod.Post, _recaptchaOptions.Url);

            var parameters = new Dictionary <string, string>()
            {
                { "secret", _recaptchaOptions.SecretKey },
                { "response", token }
            };

            message.Content = new FormUrlEncodedContent(parameters);


            HttpResponseMessage response = await _client.SendAsync(message);

            RecaptchaResponse responseData = await response.Content.ReadAsAsync <RecaptchaResponse>();

            return(responseData.Success);
        }
Exemple #18
0
        public static async Task ProcessCaptchaOrThrowAsync(this HttpRequest request)
        {
            if (Engine.Settings.Integrations.EnableGoogleRecaptcha)
            {
                var captcha = request.Form["g-recaptcha-response"].FirstOrDefault();
                if (captcha.IsSet())
                {
                    // process the captcha.
                    using (var client = new HttpClient())
                    {
                        var remoteIpAddress = request.HttpContext.Connection.RemoteIpAddress.ToString();
                        var values          = new Dictionary <string, string>
                        {
                            { "secret", Engine.Settings.Integrations.GoogleRecaptchaSecretKey },
                            { "response", captcha },
                            { "remoteip", remoteIpAddress }
                        };

                        var content = new FormUrlEncodedContent(values);

                        var responseContent = await client.PostAsync("https://www.google.com/recaptcha/api/siteverify", content);

                        var responseString = await responseContent.Content.ReadAsStringAsync();

                        RecaptchaResponse response = JsonConvert.DeserializeObject <RecaptchaResponse>(responseString);

                        if (!response.success)
                        {
                            throw new Exception("Sorry, your reCaptcha validation failed.");
                        }

                        if (request.Host.Host != response.hostname)
                        {
                            throw new Exception("Sorry, your reCaptcha validation failed, your host name does not match the validated host name.");
                        }
                    }
                }
                else
                {
                    throw new Exception("Sorry, your reCaptcha validation failed, no captcha response found.");
                }
            }
        }
Exemple #19
0
        public async Task <DefaultCommandResponse> Handle(DoublesCompetitionResultEntryCommand command)
        {
            var status = false;
            DefaultCommandResponse response;

            this._unitOfWork.Begin();
            this._registrationUnitOfWork.Begin();

            RecaptchaResponse recaptchaResponse = null;

            try
            {
                this._validationResult = await this._validator.ValidateAsync(command);

                if (this._validationResult.IsValid)
                {
                    this._unitOfWork.SoftCommit();
                    this._registrationUnitOfWork.SoftCommit();

                    //await this._registrationEmailManager.SendConfirmationEmails(registration, this._competition);
                    status   = true;
                    response = DefaultCommandResponse.Create(this._validationResult);
                }
                else
                {
                    this._unitOfWork.Rollback();
                    this._registrationUnitOfWork.Rollback();
                    response = DefaultCommandResponse.Create(this._validationResult);
                }
            }
            catch (Exception e)
            {
                this._unitOfWork.Rollback();
                this._registrationUnitOfWork.Rollback();
                Console.WriteLine(e);
                throw;
            }

            return(response);
        }
Exemple #20
0
        public ModerationAnalysisReport NeedsModeration(Comment comment, RecaptchaResponse recaptchaResponse, AkismetResponse akismetResponse, KnownCommenterResponse knownCommenterResponse)
        {
            var reasonForModeration = new StringBuilder();

            CheckReCaptcha(recaptchaResponse, reasonForModeration);
            CheckAkismet(akismetResponse, reasonForModeration);
            CheckKnownCommenter(knownCommenterResponse, reasonForModeration);

            if (reasonForModeration.Length > 0)
            {
                _log.LogInformation("Comment needs moderation because: {0}", reasonForModeration.ToString());
            }
            else
            {
                _log.LogInformation("Comment does not need moderation");
            }

            return(new ModerationAnalysisReport
            {
                NeedsModeration = reasonForModeration.Length > 0,
                ReasonForModeration = reasonForModeration.ToString()
            });
        }
Exemple #21
0
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            Roadkill.Core.Mvc.Controllers.ControllerBase controller = filterContext.Controller as Roadkill.Core.Mvc.Controllers.ControllerBase;
            if (controller != null)
            {
                SiteSettings siteSettings = controller.SettingsService.GetSiteSettings();
                if (siteSettings.IsRecaptchaEnabled)
                {
                    string challengeValue = filterContext.HttpContext.Request.Form[CHALLENGE_KEY];
                    string responseValue  = filterContext.HttpContext.Request.Form[RESPONSE_KEY];

                    RecaptchaValidator validator = new RecaptchaValidator();
                    validator.PrivateKey = siteSettings.RecaptchaPrivateKey;
                    validator.RemoteIP   = filterContext.HttpContext.Request.UserHostAddress;
                    validator.Challenge  = challengeValue;
                    validator.Response   = responseValue;

                    RecaptchaResponse validationResponse = validator.Validate();
                    filterContext.ActionParameters["isCaptchaValid"] = validationResponse.IsValid;
                }
            }

            base.OnActionExecuting(filterContext);
        }
 /// <summary>
 /// Initializes static members of the <see cref="RecaptchaResponse"/> class.
 /// </summary>
 static RecaptchaResponse()
 {
     Valid = new RecaptchaResponse(true, string.Empty);
     RecaptchaNotReachable = new RecaptchaResponse(false, "recaptcha-not-reachable");
     InvalidSolution       = new RecaptchaResponse(false, "incorrect-captcha-sol");
 }
        public ActionResult Register(string username, string email, string password, string confirmPassword)
        {
            // Basic parameter validation
            if (String.IsNullOrEmpty(username))
            {
                ModelState.AddModelError("username", "You must specify a username.", username);
            }

            if (String.IsNullOrEmpty(email))
            {
                ModelState.AddModelError("email", "You must specify an email address.", email);
            }

            if (password == null || password.Length < this.Provider.MinRequiredPasswordLength)
            {
                string passwordError = String.Format(CultureInfo.CurrentCulture, "You must specify a new password of {0} or more characters.", this.Provider.MinRequiredPasswordLength);
                ModelState.AddModelError("password", passwordError, password);
            }

            if (!String.Equals(password, confirmPassword, StringComparison.Ordinal))
            {
                ModelState.AddModelError("_FORM", "The new password and confirmation password do not match.");
            }

            // We don't check the captcha if running localhost and no challenge was given
            if (this.Request.UserHostAddress == "127.0.0.1" && this.Request.Form["recaptcha_challenge_field"] != null)
            {
                // Check the captcha response
                RecaptchaValidator humanValidator = new RecaptchaValidator();
                humanValidator.PrivateKey = ConfigurationManager.AppSettings["RecaptchaPrivateKey"];
                humanValidator.RemoteIP   = this.Request.UserHostAddress;
                humanValidator.Challenge  = this.Request.Form["recaptcha_challenge_field"];
                humanValidator.Response   = this.Request.Form["recaptcha_response_field"];

                RecaptchaResponse humanResponse = humanValidator.Validate();
                if (!humanResponse.IsValid)
                {
                    Dictionary <string, object> props = new Dictionary <string, object>
                    {
                        { "PrivateKey", humanValidator.PrivateKey },
                        { "RemoteIP", humanValidator.RemoteIP },
                        { "Challenge", humanValidator.Challenge },
                        { "Response", humanValidator.Response },
                        { "IsValid", humanResponse.IsValid },
                        { "ErrorCode", humanResponse.ErrorCode }
                    };
                    Logger.Write("Failed reCAPTCHA attempt", "Controller", 200, 0, TraceEventType.Verbose, "Failed reCAPTCHA attempt", props);
                    ModelState.AddModelError("recaptcha", "reCAPTCHA failed to verify", humanValidator.Response);
                }
            }

            if (ViewData.ModelState.IsValid)
            {
                // Attempt to register the user
                MembershipCreateStatus    createStatus;
                CosmoMongerMembershipUser newUser = (CosmoMongerMembershipUser)this.Provider.CreateUser(username, password, email, null, null, false, null, out createStatus);

                if (newUser != null)
                {
                    return(RedirectToAction("SendVerificationCode", new RouteValueDictionary(new { username = username })));
                }
                else
                {
                    ModelState.AddModelError("_FORM", ErrorCodeToString(createStatus));
                }
            }

            // If we got this far, something failed, redisplay form
            return(View());
        }
Exemple #24
0
 public Task <ActionResult <RecaptchaResponse> > SampleApi(SampleData data, [FromRecaptchaResponse] RecaptchaResponse recaptchaResponse)
 {
     Console.WriteLine(recaptchaResponse);
     return(Task.FromResult(new ActionResult <RecaptchaResponse>(recaptchaResponse)));
 }
Exemple #25
0
 public ActionResult MultiConfigApi([FromRecaptchaResponse] RecaptchaResponse recaptchaResponse)
 {
     return(Ok(recaptchaResponse));
 }
        public async Task <DefaultIdentityCommandResponse> Handle(AddCompetitionEntrantCommand command)
        {
            var status = false;
            DefaultIdentityCommandResponse response;

            this._unitOfWork.Begin();
            this._registrationUnitOfWork.Begin();

            RecaptchaResponse recaptchaResponse = null;

            try
            {
                this._competition = await this._competitionRepository.GetForUpdate(command.CompetitionID);

                this._entrants = await this._competitionEntrantRepository.GetAll(this._competition.ID);

                Dictionary <int, Common.Domain.Entities.Player> newPlayers = await this._playerRepository.GetDictionary(command.Entrant.GetPlayerIDs().ToArray());

                var validationContext = new ValidationContext <AddCompetitionEntrantCommand>(command);
                validationContext.RootContextData.Add("Competition", this._competition);

                this._validationResult = await this._addCompetitionEntrantCommandValidator.ValidateAsync(validationContext);

                if (this._validationResult.IsValid)
                {
                    var competitionEntrant = this._competition.CreateEntrant();
                    this.AddPlayer(competitionEntrant, command.Entrant.Player1, newPlayers);
                    this.AddPlayer(competitionEntrant, command.Entrant.Player2, newPlayers);
                    this.AddPlayer(competitionEntrant, command.Entrant.Player3, newPlayers);
                    this.AddPlayer(competitionEntrant, command.Entrant.Player4, newPlayers);

                    var competitionEntrantValidationContext = new ValidationContext <CompetitionEntrant>(competitionEntrant);
                    competitionEntrantValidationContext.RootContextData.Add("Competition", this._competition);
                    competitionEntrantValidationContext.RootContextData.Add("CurrentEntrants", this._entrants);
                    this._validationResult = await this._competitionEntrantValidator.ValidateAsync(competitionEntrantValidationContext);

                    if (this._validationResult.IsValid)
                    {
                        await this._competitionEntrantRepository.Save(competitionEntrant);
                    }

                    this._unitOfWork.SoftCommit();
                    this._registrationUnitOfWork.SoftCommit();

                    status   = true;
                    response = DefaultIdentityCommandResponse.Create(this._validationResult, competitionEntrant.ID);
                }
                else
                {
                    this._unitOfWork.Rollback();
                    this._registrationUnitOfWork.Rollback();
                    response = DefaultIdentityCommandResponse.Create(this._validationResult);
                }
            }
            catch (Exception e)
            {
                this._unitOfWork.Rollback();
                this._registrationUnitOfWork.Rollback();
                Console.WriteLine(e);
                throw;
            }

            return(response);
        }
        public async Task <DefaultCommandResponse> Handle(AddCompetitionEntrantResultCommand command)
        {
            var status = false;
            DefaultCommandResponse response = new DefaultCommandResponse();

            this._unitOfWork.Begin();
            this._adminUnitOfWork.Begin();

            RecaptchaResponse recaptchaResponse = null;

            try
            {
                this._competition = await this._competitionRepository.GetForUpdate(command.CompetitionID);

                this._entrants = await this._competitionEntrantRepository.GetAll(command.CompetitionID);

                var existingResults = await this._competitionEntrantResultRepository.GetAll(command.CompetitionID);

                if (existingResults.Count > 0)
                {
                    this._validationResult.Errors.Add(new ValidationFailure("ExistingResult", "There has already been a result submitted."));
                }

                if (this._validationResult.IsValid)
                {
                    this._validationResult = await this._validator.ValidateAsync(command);
                }

                if (this._validationResult.IsValid)
                {
                    foreach (var roundResult in command.Rounds)
                    {
                        var data = new CompetitionEntrantResult();
                        data.CompetitionID                    = this._competition.ID;
                        data.SeasonID                         = this._competition.Season.ID;
                        data.CompetitionName                  = this._competition.Name;
                        data.WinnerEntrant                    = this._entrants.Single(x => x.ID == roundResult.Winner.EntrantID);
                        data.LoserEntrant                     = this._entrants.Single(x => x.ID == roundResult.Loser.EntrantID);
                        data.WinnerChalks                     = roundResult.Winner.Score.Chalks;
                        data.WinnerHandicap                   = roundResult.Winner.Score.Handicap;
                        data.LoserChalks                      = roundResult.Loser.Score.Chalks;
                        data.LoserHandicap                    = roundResult.Loser.Score.Handicap;
                        data.CompetitionRoundTypeID           = roundResult.RoundTypeID;
                        data.CompetitionEntrantResultStatusID = CompetitionEntrantResultStatuses.Pending;
                        data.SetAuditFields(this._user.ID);

                        await this._competitionEntrantResultRepository.Save(data);
                    }


                    this._unitOfWork.SoftCommit();
                    this._adminUnitOfWork.SoftCommit();
                }
                else
                {
                    this._unitOfWork.Rollback();
                    this._adminUnitOfWork.Rollback();
                }

                response = DefaultCommandResponse.Create(this._validationResult);
            }
            catch (Exception e)
            {
                this._unitOfWork.Rollback();
                this._adminUnitOfWork.Rollback();
                Console.WriteLine(e);
                throw;
            }

            return(response);
        }
Exemple #28
0
        // POST: api/CaptchaVerify
        public ReCaptchaVerifyResponse Post([FromBody] RecaptchaResponse requestParams)
        {
            var clientIp = HttpContext.Current.Request.UserHostAddress;

            return(new ReCaptcha().Validate(requestParams.Response, clientIp));
        }
 /// <summary>
 /// Initializes static members of the <see cref="RecaptchaResponse"/> class. 
 /// </summary>
 static RecaptchaResponse()
 {
     Valid = new RecaptchaResponse(true, string.Empty);
     RecaptchaNotReachable = new RecaptchaResponse(false, "recaptcha-not-reachable");
     InvalidSolution = new RecaptchaResponse(false, "incorrect-captcha-sol");
 }
        public async Task <DefaultCommandResponse> Handle(CreateDoublesRegistrationCommand command)
        {
            var attempt = await this.StoreAttempt(command);

            var status = false;
            DefaultCommandResponse response;

            this._unitOfWork.Begin();
            this._registrationUnitOfWork.Begin();

            RecaptchaResponse recaptchaResponse = null;

            try
            {
                CompetitionRegistration registration = null;
                this._validationResult = this._validator.Validate(command);

                if (this._validationResult.IsValid)
                {
                    await this.Load(command);

                    RegistrationValidatorHelper.Validate(this._validationResult, this._competition);
                }

                if (this._validationResult.IsValid)
                {
                    RegistrationValidatorHelper.ValidateGameFormat(this._validationResult, this._competition, GameFormats.Doubles);
                }

                if (this._validationResult.IsValid)
                {
                    recaptchaResponse = await this._recaptchaService.Validate(command.Registration, "opens/registration", this._validationResult);
                }

                if (this._validationResult.IsValid)
                {
                    registration = this._competition.CreateRegistration(command.Registration.Contact.Forename, command.Registration.Contact.Surname, command.Registration.Contact.EmailAddress);

                    foreach (var player in command.Registration.Players)
                    {
                        var entrant = registration.CreateEntrant(this._competition);
                        entrant.CreatePlayer(player.Player1.Forename, player.Player1.Surname);
                        entrant.CreatePlayer(player.Player2.Forename, player.Player2.Surname);
                        if (player.QualificationDate.HasValue)
                        {
                            entrant.CompetitionDateID = player.QualificationDate.Value;
                        }
                    }

                    await this._competitionRegistrationRepository.Save(registration);
                }

                if (this._validationResult.IsValid)
                {
                    this._unitOfWork.SoftCommit();
                    this._registrationUnitOfWork.SoftCommit();

                    await this._registrationEmailManager.SendConfirmationEmails(registration, this._competition);

                    status   = true;
                    response = DefaultCommandResponse.Create(this._validationResult);
                    this.StoreAttemptResponse(attempt, response);
                }
                else
                {
                    this._unitOfWork.Rollback();
                    this._registrationUnitOfWork.Rollback();
                    response = DefaultCommandResponse.Create(this._validationResult);
                    this.StoreAttemptResponse(attempt, response);
                }
            }
            catch (Exception e)
            {
                this._unitOfWork.Rollback();
                this._registrationUnitOfWork.Rollback();
                Console.WriteLine(e);
                throw;
            }
            finally
            {
                if (recaptchaResponse != null && recaptchaResponse.Data != null)
                {
                    attempt.RecaptchaScore = recaptchaResponse.Data.Score;
                }

                attempt.Status = status;
                await this._competitionRegistrationAttemptRepository.Save(attempt);
            }

            return(response);
        }
Exemple #31
0
        /// <summary>
        /// The validate.
        /// </summary>
        public void Validate()
        {
            if (this.skipRecaptcha)
            {
                this.recaptchaResponse = RecaptchaResponse.Valid;
            }

            if (this.recaptchaResponse != null)
            {
                return;
            }

            var validator = new RecaptchaValidator
                                {
                                    SecretKey = this.SecretKey,
                                    RemoteIP = this.Page.Request.GetUserRealIPAddress(),
                                    Response = this.Context.Request.Form["g-recaptcha-response"]
                                };
            try
            {
                this.recaptchaResponse = validator.Validate();
            }
            catch (ArgumentNullException exception)
            {
                this.recaptchaResponse = null;
                this.errorMessage = exception.Message;
            }
        }
        public async Task <IActionResult> Index(UserEmailDetails userEmail)
        {
            _logger.LogDebug($"{GetType().Name}.{nameof(Index)} method called...");
            ViewData["ErrorMessage"] = string.Empty;

            RecaptchaResponse recaptcha = await _recaptcha.Validate(Request);

            IActionResult result = View();

            if (!recaptcha.success)
            {
                ViewData["ErrorMessage"] = $"There was an error validating reCAPTCHA. Please try again!";
                ModelState.AddModelError("", "There was an error validating reCAPTCHA. Please try again!");
            }
            else
            {
                try
                {
                    if (!string.IsNullOrEmpty(userEmail?.Email))
                    {
                        EmailList emailListItem = new EmailList()
                        {
                            Id          = Guid.NewGuid(),
                            Email       = userEmail.Email,
                            IsValidated = false,
                            DateCreated = DateTime.UtcNow
                        };

                        _emailListRepository.Add(emailListItem);
                        _unitOfWork.Save();

                        if (!await SendEmailMessage(this.HttpContext, emailListItem.Id, emailListItem.Email))
                        {
                            ViewData["ErrorMessage"] = "Unable to send confirmation email";
                        }
                        else
                        {
                            this.HttpContext.Session.Set("Email", Encoding.UTF8.GetBytes(userEmail.Email));

                            result = Redirect($"/Home/ValidateEmail/?e={userEmail?.Email}");
                        }
                    }
                }
                catch (DbUpdateException ex)
                {
                    _logger.LogError(ex, ex.Message);
                    ViewData["ErrorMessage"] = "This email has already been submitted.";
                }
                catch (SqlException ex)
                {
                    _logger.LogError(ex, ex.Message);
                    if (ex.Message.ToLower().Contains("cannot insert duplicate key"))
                    {
                        ViewData["ErrorMessage"] = "This email has already been submitted.";
                    }
                    else
                    {
                        ViewData["ErrorMessage"] = "There was a critical failure saving to the database.";
                    }
                }
            }

            return(result);
        }