public void MissingContext()
        {
            var options = GetOptions();
            var service = new RecaptchaService(options);

            var ex = Assert.Throws <ArgumentNullException>(() => new RecaptchaScriptTagHelper(service, null));
        }
Example #2
0
        public ContactResult Submit(ContactModel contact, ContactSettings contactSettings)
        {
            var result = new ContactResult();
            if (contact == null) throw new ArgumentNullException("Missing contact form data");
            if (contactSettings == null) throw new ArgumentNullException("Missing settings");

            if (logger != null) logger.LogInformation("Contact: {0} / {1} / {2} [Email: {3}, Post: {4}, Recaptcha: {5}]",
                contact.ContactName, contact.Email, contact.Phone, contactSettings.EmailSettings?.Enabled,
                contactSettings.PostSettings?.Enabled, contactSettings.RecaptchaSettings?.Enabled);

            if (contactSettings.RecaptchaSettings != null
                && contactSettings.RecaptchaSettings.Enabled
                && !string.IsNullOrEmpty(contactSettings.RecaptchaSettings.RecaptchaKey))
            {
                // Check Recaptcha
                var recaptchaService = new RecaptchaService();
                result.RecaptchaResult = recaptchaService.Validate(contactSettings.RecaptchaSettings, logger);
                if (result.RecaptchaResult.ServiceResultType != ServiceResultType.Success) return result;  // Stop processing immediately
            }

            if (contactSettings.EmailSettings != null && contactSettings.EmailSettings.Enabled)
            {
                var emailService = new EmailService();
                result.EmailResult = emailService.SendEmail(contact, contactSettings.EmailSettings, logger);
            }

            if (contactSettings.PostSettings != null && contactSettings.PostSettings.Enabled && !string.IsNullOrEmpty(contactSettings.PostSettings.PostURL))
            {
                var postService = new PostService();
                result.PostResult = postService.Post(contact, contactSettings.PostSettings, logger);
            }
            return result;
        }
Example #3
0
        public async Task ValidateRecaptchaResponse_ShouldReturn_HttpRequestError()
        {
            // Arrange
            _httpMessageHandlerMock = new Mock <HttpMessageHandler>();
            _httpMessageHandlerMock.Protected()
            .Setup <Task <HttpResponseMessage> >(
                "SendAsync",
                ItExpr.IsAny <HttpRequestMessage>(),
                ItExpr.IsAny <CancellationToken>()
                )
            .ReturnsAsync(new HttpResponseMessage()
            {
                StatusCode = HttpStatusCode.BadRequest
            })
            .Verifiable();

            _httpClient = new HttpClient(_httpMessageHandlerMock.Object)
            {
                BaseAddress = new Uri("http://test.com/"),
            };

            var service = new RecaptchaService(_settingsMock.Object, _httpClient, _logger);

            // Act
            var response = await service.ValidateRecaptchaResponse(Token);

            // Assert
            _httpMessageHandlerMock.Verify();
            Assert.GreaterOrEqual(response.Errors.Count(), 1);
            Assert.AreEqual(ValidationError.HttpRequestFailed, response.Errors.First());
        }
        public void NoOptions()
        {
            var options           = GetOptions();
            var src               = Guid.NewGuid().ToString();
            var validationMessage = Guid.NewGuid().ToString();

            options.Value.JavaScriptUrl     = src;
            options.Value.ValidationMessage = validationMessage;
            var service             = new RecaptchaService(options);
            var httpContext         = new DefaultHttpContext();
            var httpContextAccessor = new Mock <IHttpContextAccessor>(MockBehavior.Strict);

            httpContextAccessor
            .Setup(a => a.HttpContext)
            .Returns(httpContext)
            .Verifiable();

            var output = ProcessTagHelper(service, httpContextAccessor.Object, new TagHelperAttributeList());

            Assert.Equal("script", output.TagName);
            Assert.Equal(TagMode.StartTagAndEndTag, output.TagMode);
            Assert.NotNull(output.Attributes["src"]);
            Assert.Equal(src, output.Attributes["src"].Value);
            Assert.NotNull(output.Attributes["async"]);
            Assert.Equal(string.Empty, output.Attributes["async"].Value);
            Assert.NotNull(output.Attributes["defer"]);
            Assert.Equal(string.Empty, output.Attributes["defer"].Value);
            Assert.Equal(string.Format(_script, "recaptchaValidated", string.Empty, validationMessage), output.PostElement.GetContent());

            httpContextAccessor.Verify();
        }
Example #5
0
 public ValidateRecaptchaFilter(IServiceProvider services, double minimumScore, string errorMessage)
 {
     _recaptcha          = services.GetRequiredService <RecaptchaService>();
     _webHostEnvironment = services.GetRequiredService <IWebHostEnvironment>();
     _minimumScore       = minimumScore;
     _errorMessage       = errorMessage;
 }
        public HttpResponseMessage ValidateCaptcha(RecaptchaPostRequest model)
        {
            //check if the model is valid
            if (!ModelState.IsValid)
            {
                //add to error log
                ErrorLogService    svc   = new ErrorLogService();
                ErrorLogAddRequest error = new ErrorLogAddRequest();
                error.ErrorFunction = "Sabio.Web.Controllers.Api.ValidateCaptcha";
                error.ErrorMessage  = ModelState.ToString();
                error.UserId        = UserService.UserSelect().PersonId;
                svc.ErrorLogInsert(error);
                //if the model isn't valid, return a error response
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
            }

            //instantiate the item response model
            ItemResponse <bool> response = new ItemResponse <bool>();

            //grab the values from the model
            string key     = model.secret;
            string request = model.response;

            //send POST request via the service we made which returns a bool
            bool isCaptchaValid = RecaptchaService.Validate(request, key);

            //save the bool value in our response model
            response.Item = isCaptchaValid;

            //return the response
            return(Request.CreateResponse(HttpStatusCode.OK, response));
        }
Example #7
0
        public void ValidateRecaptchaResponse_ShouldThrowAnyOtherThan_HttpRequestException()
        {
            // Arrange
            _httpMessageHandlerMock = new Mock <HttpMessageHandler>();
            _httpMessageHandlerMock.Protected()
            .Setup <Task <HttpResponseMessage> >(
                "SendAsync",
                ItExpr.IsAny <HttpRequestMessage>(),
                ItExpr.IsAny <CancellationToken>()
                )
            .ThrowsAsync(new Exception())
            .Verifiable();

            _httpClient = new HttpClient(_httpMessageHandlerMock.Object)
            {
                BaseAddress = new Uri("http://test.com/"),
            };

            var service = new RecaptchaService(_settingsMock.Object, _httpClient, _logger);

            // Act


            // Assert
            Assert.ThrowsAsync <Exception>(() => service.ValidateRecaptchaResponse(Token));
            _httpMessageHandlerMock.Verify();
        }
Example #8
0
        public void GetSiteKeySuccess()
        {
            var options = GetOptions();

            var service = new RecaptchaService(options);

            Assert.Equal(options.Value.SiteKey, service.SiteKey);
        }
Example #9
0
        public void GetJavaScriptUrlSuccess()
        {
            var options = GetOptions();

            var service = new RecaptchaService(options);

            Assert.Equal(options.Value.JavaScriptUrl, service.JavaScriptUrl);
        }
Example #10
0
        public void GetEnabledSuccess()
        {
            var options = GetOptions();

            var service = new RecaptchaService(options);

            Assert.Equal(options.Value.Enabled, service.Enabled);
        }
Example #11
0
        public void EnForceDefaultControlSettings()
        {
            var options = GetOptions();

            options.Value.ControlSettings = null;

            var service = new RecaptchaService(options);

            Assert.NotNull(service.ControlSettings);
        }
Example #12
0
        public void ValidateRecaptchaResponse_ShouldThrow_ArgumentNullException()
        {
            // Arrange
            var service = new RecaptchaService(_settingsMock.Object, _httpClient, _logger);

            // Act


            // Assert
            Assert.ThrowsAsync <ArgumentNullException>(() => service.ValidateRecaptchaResponse(null));
        }
Example #13
0
        public void Construction_IsSuccessful()
        {
            // Arrange


            // Act
            var instance = new RecaptchaService(_settingsMock.Object, _httpClient, _logger);

            // Assert
            Assert.NotNull(instance);
            _settingsMock.Verify(settings => settings.CurrentValue, Times.Once);
        }
Example #14
0
        public void DoNotRenderIfDisabled()
        {
            var options = GetOptions();

            options.Value.Enabled = false;
            var service = new RecaptchaService(options);

            var output = ProcessTagHelper(service, new TagHelperAttributeList());

            Assert.Null(output.TagName);
            Assert.False(output.IsContentModified);
            Assert.Empty(output.Attributes);
        }
Example #15
0
        public async Task ValidateRecaptchaResponse_ShouldReturn_DeserializedResponse()
        {
            // Arrange
            var service = new RecaptchaService(_settingsMock.Object, _httpClient, _logger);

            // Act
            var response = await service.ValidateRecaptchaResponse(Token);

            // Assert
            _httpMessageHandlerMock.Verify();
            Assert.IsTrue(response.Success);
            Assert.AreEqual(0, response.Errors.Count());
        }
        public HttpResponseMessage sendCaptcha(RecaptchaRequest model)
        {
            if (!ModelState.IsValid)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
            }

            ItemResponse <bool> response = new ItemResponse <bool>();

            string key     = model.secret;
            string request = model.response;

            bool isCaptchaValid = RecaptchaService.Validate(request, key);

            response.Item = isCaptchaValid;

            return(Request.CreateResponse(HttpStatusCode.OK, response));
        }
Example #17
0
        public void ChangeSuccess()
        {
            var options = GetOptions();

            var service = new RecaptchaService(options);

            Assert.Equal(Resources.Default_ValidationMessage, service.ValidationMessage);

            var newValidationMessage = Guid.NewGuid().ToString();

            options.Value.ValidationMessage = newValidationMessage;

            Assert.Equal(newValidationMessage, service.ValidationMessage);

            options.Value.ValidationMessage = null;

            Assert.Equal(Resources.Default_ValidationMessage, service.ValidationMessage);
        }
Example #18
0
        public IActionResult OnPost()
        {
            // Call custom validator
            var validator = new ContactModelValidator();
            var results   = validator.Validate(ContactModel);

            results.AddToModelState(ModelState, "ContactModel.");

            // Check Recaptcha
            if (settings.RecaptchaEnabled)
            {
                var recaptchaService  = new RecaptchaService();
                var recaptchaResponse = recaptchaService.Validate(
                    new RecaptchaSettings
                {
                    Enabled           = true,
                    RecaptchaKey      = settings.RecaptchaSecretKey,
                    RecaptchaResponse = Request.Form["g-recaptcha-response"]
                }, logger);

                if (recaptchaResponse.ServiceResultType != ServiceResultType.Success)
                {
                    ModelState.AddModelError("Recaptcha", recaptchaResponse.Message);
                }
            }

            if (!ModelState.IsValid)
            {
                return(Page());
            }

            HttpContent content  = new StringContent(JsonConvert.SerializeObject(ContactModel), Encoding.UTF8, "application/json");
            var         resultOk = post.Post(settings.APIEndpoint, content) && post.Post(settings.ContactFormWebEndpoint, content);

            if (resultOk)
            {
                return(new RedirectToPageResult("ContactCS", new { s = 1 }));
            }
            else
            {
                Message = "Error calling API.";
                return(Page());
            }
        }
        public void NoOptions()
        {
            var service = new RecaptchaService(GetOptions());

            var output = ProcessTagHelper(service, new TagHelperAttributeList());

            Assert.Equal("div", output.TagName);
            Assert.Equal(TagMode.StartTagAndEndTag, output.TagMode);
            Assert.NotNull(output.Attributes["class"]);
            Assert.Equal("g-recaptcha", output.Attributes["class"].Value);
            Assert.NotNull(output.Attributes["data-sitekey"]);
            Assert.Equal(_siteKey, output.Attributes["data-sitekey"].Value);
            Assert.NotNull(output.Attributes["data-callback"]);
            Assert.Equal("recaptchaValidated", output.Attributes["data-callback"].Value);
            Assert.Null(output.Attributes["data-theme"]);
            Assert.Null(output.Attributes["data-type"]);
            Assert.Null(output.Attributes["data-size"]);
            Assert.Null(output.Attributes["data-tabindex"]);
        }
Example #20
0
        private static async Task <VerifyResponse> Verify(string secretKey, string responseToken)
        {
            var options = Options.Create(new RecaptchaOptions()
            {
                SecretKey = secretKey
            });

            var recaptchaClient = RestService.For <IRecaptchaClient>(
                new HttpClient()
            {
                BaseAddress = new Uri("https://www.google.com/recaptcha/api")
            },
                new RefitSettings(new NewtonsoftJsonContentSerializer()));

            IRecaptchaService recaptchaService = new RecaptchaService(options, recaptchaClient);

            var response = await recaptchaService.VerifyAsync(responseToken);

            return(response);
        }
        public void DoNotRenderIfDisabled()
        {
            var options = GetOptions();

            options.Value.Enabled = false;
            var service             = new RecaptchaService(options);
            var httpContext         = new DefaultHttpContext();
            var httpContextAccessor = new Mock <IHttpContextAccessor>(MockBehavior.Strict);

            httpContextAccessor
            .Setup(a => a.HttpContext)
            .Returns(httpContext)
            .Verifiable();

            var output = ProcessTagHelper(service, httpContextAccessor.Object, new TagHelperAttributeList());

            Assert.Null(output.TagName);
            Assert.False(output.IsContentModified);
            Assert.Empty(output.Attributes);
        }
Example #22
0
 public LoginModule(EntityArea area, LoginModuleSettings settings, string name = null) : base(area, name ?? "LoginModule", "Login module", version: CurrentVersion)
 {
     _settings = settings;
     App.RegisterConfig(_settings);
     //Register entities
     RegisterEntities(typeof(ILogin), typeof(ISecretQuestion), typeof(ISecretQuestionAnswer), typeof(ITrustedDevice),
                      typeof(ILoginExtraFactor), typeof(IPasswordHistory), typeof(ILoginProcess));
     //Register services
     App.RegisterService <ILoginService>(this);
     App.RegisterService <ILoginProcessService>(this);
     App.RegisterService <ILoginManagementService>(this);
     App.RegisterService <ILoginAdministrationService>(this);
     RegisterSize("EventType", 50);
     Roles = new LoginAuthorizationRoles();
     // Create recaptcha service if settings are there
     if (_settings.Recaptcha != null)
     {
         var recaptcha = new RecaptchaService(_settings.Recaptcha);
         App.RegisterService <IRecaptchaService>(recaptcha);
     }
 }
        public void TabIndexOptions()
        {
            var service = new RecaptchaService(GetOptions());
            var ran     = new Random(DateTime.Now.Millisecond);
            var index   = ran.Next(1000);

            var output = ProcessTagHelper(service, new TagHelperAttributeList(), (th) => th.TabIndex = index);

            Assert.Equal("div", output.TagName);
            Assert.Equal(TagMode.StartTagAndEndTag, output.TagMode);
            Assert.NotNull(output.Attributes["class"]);
            Assert.Equal("g-recaptcha", output.Attributes["class"].Value);
            Assert.NotNull(output.Attributes["data-sitekey"]);
            Assert.Equal(_siteKey, output.Attributes["data-sitekey"].Value);
            Assert.NotNull(output.Attributes["data-callback"]);
            Assert.Equal("recaptchaValidated", output.Attributes["data-callback"].Value);
            Assert.Null(output.Attributes["data-theme"]);
            Assert.Null(output.Attributes["data-type"]);
            Assert.Null(output.Attributes["data-size"]);
            Assert.NotNull(output.Attributes["data-tabindex"]);
            Assert.Equal(index, output.Attributes["data-tabindex"].Value);
        }
        private TagHelperOutput ProcessTagHelper(RecaptchaService service, IHttpContextAccessor httpContextAccessor, TagHelperAttributeList attributes, Action <RecaptchaScriptTagHelper> config = null)
        {
            var tagHelper = new RecaptchaScriptTagHelper(service, httpContextAccessor);

            config?.Invoke(tagHelper);

            var tagHelperContext = new TagHelperContext(
                allAttributes: new TagHelperAttributeList(),
                items: new Dictionary <object, object>(),
                uniqueId: "test");

            var output = new TagHelperOutput(
                tagName: "doesntmatter",
                attributes: attributes,
                getChildContentAsync: (useCachedResult, encoder) =>
            {
                return(Task.FromResult <TagHelperContent>(new DefaultTagHelperContent()));
            });

            tagHelper.Process(tagHelperContext, output);

            return(output);
        }
        public IActionResult OnPost([FromBody] ContactModel ContactModel)
        {
            // Call custom validator
            var validator = new ContactModelValidator();
            var results   = validator.Validate(ContactModel);

            results.AddToModelState(ModelState, null);

            // Check Recaptcha
            if (settings.RecaptchaEnabled)
            {
                var recaptchaService  = new RecaptchaService();
                var recaptchaResponse = recaptchaService.Validate(
                    new RecaptchaSettings
                {
                    Enabled           = true,
                    RecaptchaKey      = settings.RecaptchaSecretKey,
                    RecaptchaResponse = ContactModel.RecaptchaResponse
                }, logger);

                if (recaptchaResponse.ServiceResultType != ServiceResultType.Success)
                {
                    ModelState.AddModelError("Recaptcha", recaptchaResponse.Message);
                }
            }

            if (!ModelState.IsValid)
            {
                return(new JsonResult(ModelState.Values));
            }

            HttpContent content  = new StringContent(JsonConvert.SerializeObject(ContactModel), Encoding.UTF8, "application/json");
            var         resultOk = post.Post(settings.APIEndpoint, content) && post.Post(settings.ContactFormWebEndpoint, content);

            return(new JsonResult(new { Status = resultOk ? "OK" : "Error calling API." }));
        }
            private void InitService()
            {
                var http = _httpHandler.CreateClient();

                _service = new RecaptchaService(http, _mockConfig.Object);
            }
Example #27
0
 public CollectionsController(CollectionService collection, RecaptchaService recaptcha)
 {
     this.collectionService = collection;
     this.recaptchaService  = recaptcha;
 }
Example #28
0
 public PersonController(IRecaptchaService recaptcha, IOptions <RecaptchaOptions> recaptchaOptions)
 {
     this.recaptcha        = recaptcha as RecaptchaService;
     this.recaptchaOptions = recaptchaOptions.Value;
 }
Example #29
0
 public UsersController(UserService userService, RecaptchaService recaptchaService)
 {
     this.userService      = userService;
     this.recaptchaService = recaptchaService;
 }
Example #30
0
        public RecaptchaInvisibleScriptTagHelper(RecaptchaService service)
        {
            service.CheckArgumentNull(nameof(service));

            _service = service;
        }