Exemplo n.º 1
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log, ExecutionContext context)
        {
            var formContents = await FormContentsFactory.Create(req);

            var comment  = CommentFactory.Create(formContents);
            var settings = SettingsFactory.Create(formContents.Options.Origin, log);

            var reCaptcha         = new ReCaptchaService(settings.ReCaptchaSecretKey, log);
            var reCaptchaResponse = await reCaptcha.Validate(formContents.Options.Recaptcha.Token);

            var akismetService  = new AkismetService(settings, log);
            var akismetResponse = await akismetService.IsSpam(req, comment, formContents);

            var gitHubService = new GitHubService(settings.GitHubOwner, settings.GitHubRepository, settings.GitHubBranch,
                                                  settings.GitHubCommentPath, settings.GitHubToken);
            var knownCommenterResponse = await gitHubService.IsKnownCommenter(comment.Name, comment.Email);

            var analyzer       = new ModerationAnalyzer(settings, log);
            var analysisReport = analyzer.NeedsModeration(comment, reCaptchaResponse, akismetResponse, knownCommenterResponse);

            await gitHubService.AddComment(comment, analysisReport, knownCommenterResponse);

            return(new OkResult());
        }
Exemplo n.º 2
0
        public HomeController(WordInSentencesService wordInSentencesService, ReCaptchaService recaptchaService, BookSearchService bookSearchService, APIService apiService)
        {
            _wordInSentencesService = wordInSentencesService ?? throw new ArgumentNullException(nameof(wordInSentencesService));
            _recaptchaService = recaptchaService ?? throw new ArgumentNullException(nameof(recaptchaService));
            _bookSearchService = bookSearchService ?? throw new ArgumentNullException(nameof(bookSearchService));
			_apiService = apiService ?? throw new ArgumentNullException(nameof(apiService));
        }
Exemplo n.º 3
0
        private async Task VerifyCaptcha(CancellationToken cancellationToken)
        {
            var captchaService = new ReCaptchaService();

            var clientToken = this.GetClientToken();
            var ipAddress   = this.GetClientIPAddress();

            var result = await captchaService.Verify3Async(clientToken, ipAddress, CaptchaSettings.SecretKey, cancellationToken);

            if (result == null)
            {
                SetStatus("ERROR: Verification result is null.", Color.Red);
                return;
            }

            if (!result.IsSuccess ||
                result.Action != PageAction ||
                result.Score < 0.5)
            {
                SetStatus("ERROR: Something went wrong. I think you're a bot!", Color.Red);
                return;
            }

            var now = DateTime.Now;

            SetStatus("Cool. Validation passed. Time is: " + now + ". Your message is: " + this.message.Text, Color.Lime);
        }
Exemplo n.º 4
0
        public void ThrowsIfSecretKeyIsNotSet()
        {
            var verificationService = new ReCaptchaService(new MockHttpService(), new ReCoreOptions());
            var exception           = Assert.Throws <Exception>(() => new ReCoreFilter(new ReCoreOptions(), verificationService));

            Assert.Equal(Strings.SECRET_KEY_REQUIRED, exception.Message);
        }
        public async Task can_make_good_request()
        {
            var service = new ReCaptchaService();

            service.EnableFiddlerDebugProxy("http://localhost.:8888");

            //response.IsSuccess.Should().BeTrue();
        }
Exemplo n.º 6
0
 public UserFacade(AppDbContext context, ConfigEnvironment config)
 {
     _userService          = new UserService(context);
     _invitationKeyService = new InvitationKeyService(context);
     _emailService         = new EmailService(EmailType.BlueGray);
     _reCaptchaService     = new ReCaptchaService();
     _config = config;
 }
        protected void vcustCaptcha_ServerValidate(object source, ServerValidateEventArgs args)
        {
            bool             status       = false;
            ReCaptchaService recaptchaObj = new ReCaptchaService();

            status       = recaptchaObj.getReCaptchaStatus(Request["g-recaptcha-response"]);
            args.IsValid = status;
        }
        public async Task can_make_process_bad_request()
        {
            var service = new ReCaptchaService();

            service.EnableFiddlerDebugProxy("http://localhost.:8888");

            var response = await service.Verify3Async("ffff", "127.0.0.1", "bbbb");

            response.IsSuccess.Should().BeFalse();
        }
Exemplo n.º 9
0
 public ValidateReCaptchaTask(
     ReCaptchaService reCaptchaService,
     IUpdateModelAccessor updateModelAccessor,
     IStringLocalizer <ValidateReCaptchaTask> localizer
     )
 {
     _reCaptchaService    = reCaptchaService;
     _updateModelAccessor = updateModelAccessor;
     S = localizer;
 }
Exemplo n.º 10
0
        public async Task <IActionResult> OnPost()
        {
            Input.IpAddress = httpContext?.Connection?.RemoteIpAddress?.MapToIPv4()?.ToString();

            var service  = new ReCaptchaService(Environment.GetEnvironmentVariable("RECAPTCHA_SECRET"));
            var response = await service.VerifyAsync(Input.Token, Input.IpAddress);

            Input.ApiResponse = Utf8Json.JsonSerializer.ToJsonString(response);
            return(Page());
        }
Exemplo n.º 11
0
        private async Task <bool> Verify(string captchaResponse, IPAddress clientIp)
        {
            if (string.IsNullOrEmpty(captchaResponse) || clientIp is null)
            {
                return(false);
            }
            var captchaApi = new ReCaptchaService();

            return(await captchaApi.Verify2Async(captchaResponse, clientIp.ToString(), _recaptchaSettings.Value.SecretKey));
        }
 public LoginModel(
     SignInManager <User> signInManager,
     ILogger <LoginModel> logger,
     UserManager <User> userManager,
     ReCaptchaService recaptchaService)
 {
     this.userManager      = userManager;
     this.recaptchaService = recaptchaService;
     this.signInManager    = signInManager;
     this.logger           = logger;
 }
Exemplo n.º 13
0
 public ReCaptchaLoginFilter(
     ILayoutAccessor layoutAccessor,
     ISiteService siteService,
     ReCaptchaService reCaptchaService,
     IShapeFactory shapeFactory)
 {
     _layoutAccessor   = layoutAccessor;
     _siteService      = siteService;
     _reCaptchaService = reCaptchaService;
     _shapeFactory     = shapeFactory;
 }
Exemplo n.º 14
0
        public void ThrowsIfOptsAreNull()
        {
            var services = new ServiceCollection();

            services.AddHttpClient();
            var provider = services.BuildServiceProvider();

            var service = new ReCaptchaService(new MockHttpService(), new ReCoreOptions());

            Assert.Throws <ArgumentNullException>(() => new ReCoreFilter(null, service));
        }
Exemplo n.º 15
0
        public void ValidateResponse_InvalidResponseWithNull()
        {
            var mock = new Mock <IRestClient>();

            mock.Setup(x => x.Execute(It.IsAny <IRestRequest>()))
            .Returns((IRestResponse)null);

            var client   = new ReCaptchaService(mock.Object);
            var response = client.ValidateResponse(TestKey, TestResponse, TestIpAddress);

            Assert.IsTrue(response == ReCaptchaValidationResult.InvalidResponse);
        }
Exemplo n.º 16
0
 public ValidateReCaptchaTask(
     IHttpContextAccessor httpContextAccessor,
     ReCaptchaService reCaptchaService,
     IUpdateModelAccessor updateModelAccessor,
     IStringLocalizer <ValidateReCaptchaTask> localizer
     )
 {
     _httpContextAccessor = httpContextAccessor;
     _reCaptchaService    = reCaptchaService;
     _updateModelAccessor = updateModelAccessor;
     T = localizer;
 }
Exemplo n.º 17
0
        public void ValidateResponse_SuccessResponse()
        {
            var mock = new Mock <IRestClient>();

            mock.Setup(x => x.Execute(It.IsAny <IRestRequest>()))
            .Returns(new RestResponse {
                Content = "{success:true}"
            });

            var client   = new ReCaptchaService(mock.Object);
            var response = client.ValidateResponse(TestKey, TestResponse, TestIpAddress);

            Assert.IsTrue(response == ReCaptchaValidationResult.Success);
        }
Exemplo n.º 18
0
        public async Task can_parse_errors()
        {
            var mockHttp = new MockHttpMessageHandler();

            mockHttp.Expect(HttpMethod.Post, Constants.VerifyUrl)
            .Respond("application/json", ErrorJson)
            .WithExactFormData("response=aaa&remoteip=bbb&secret=ccc");

            var captcha = new ReCaptchaService(client: mockHttp.ToHttpClient());

            var response = await captcha.Verify3Async("aaa", "bbb", "ccc");

            response.IsSuccess.Should().BeFalse();
            response.ErrorCodes.Should().BeEquivalentTo("invalid-input-response", "invalid-input-secret");
        }
 public RegisterModel(
     UserManager <User> userManager,
     SignInManager <User> signInManager,
     ILogger <RegisterModel> logger,
     IEmailSender emailSender,
     IWebHostEnvironment env,
     ReCaptchaService recaptchaService)
 {
     this.userManager      = userManager;
     this.signInManager    = signInManager;
     this.logger           = logger;
     this.emailSender      = emailSender;
     this.env              = env;
     this.recaptchaService = recaptchaService;
 }
Exemplo n.º 20
0
        public async Task can_verify_failed_response()
        {
            var responseJson = ResponseJson(false);

            var mockHttp = new MockHttpMessageHandler();

            mockHttp.Expect(HttpMethod.Post, Constants.VerifyUrl)
            .Respond("application/json", responseJson)
            .WithExactFormData("response=aaaaa&remoteip=bbbb&secret=cccc");

            var captcha = new ReCaptchaService(client: mockHttp.ToHttpClient());

            var response = await captcha.Verify2Async("aaaaa", "bbbb", "cccc");

            response.Should().BeFalse();

            mockHttp.VerifyNoOutstandingExpectation();
        }
Exemplo n.º 21
0
        public async Task <IHttpActionResult> Register(RegisterBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            // Validate Recaptcha
            var reCaptchaVerfiyUrl = ConfigurationManager.AppSettings["ReCaptchaVerfiyUrl"];
            var reCaptchaSecretKey = ConfigurationManager.AppSettings["ReCaptchaSecretKey"];

            if (!string.IsNullOrEmpty(reCaptchaVerfiyUrl) && !string.IsNullOrEmpty(reCaptchaSecretKey))
            {
                var remoteIpAddress  = Request.GetOwinContext().Request.RemoteIpAddress;
                var reCaptchaService = new ReCaptchaService(new RestClient(reCaptchaVerfiyUrl));

                var validationResults = reCaptchaService.ValidateResponse(reCaptchaSecretKey, model.ReCaptchaResponse, remoteIpAddress);
                if (validationResults != ReCaptchaValidationResult.Disabled && validationResults != ReCaptchaValidationResult.Success)
                {
                    ModelState.AddModelError("ReCaptchaResponse", new Exception("Unable to validate reCaptcha Response"));
                    return(BadRequest(ModelState));
                }
            }

            // Add User
            var user = new ApplicationUser()
            {
                UserName = model.Email, Email = model.Email
            };

            user.Organizations.Add(new OrganizationMembership {
                EIN = model.EIN, IsAdmin = true
            });

            IdentityResult result = await UserManager.CreateAsync(user, model.Password);

            if (!result.Succeeded)
            {
                return(GetErrorResult(result));
            }

            return(Ok());
        }
Exemplo n.º 22
0
        public async Task can_parse_good_response()
        {
            var mockHttp = new MockHttpMessageHandler();

            mockHttp.Expect(HttpMethod.Post, Constants.VerifyUrl)
            .Respond("application/json", GoodJson)
            .WithExactFormData("response=aaa&remoteip=bbb&secret=ccc");

            var captcha = new ReCaptchaService(client: mockHttp.ToHttpClient());

            var response = await captcha.Verify3Async("aaa", "bbb", "ccc");

            response.IsSuccess.Should().BeTrue();
            response.ErrorCodes.Should().BeNull();
            response.ChallengeTs.Should().Be("2019-04-30T02:37:21Z");
            response.HostName.Should().Be("www.bitarmory.com");
            response.Score.Should().Be(0.9f);
            response.Action.Should().Be("purchase");
        }
 public PasswordRecoveryFormEventEventHandler(ReCaptchaService recaptchaService)
 {
     _recaptchaService = recaptchaService;
 }
 public LoginFormEventEventHandler(ReCaptchaService reCaptchaService)
 {
     _reCaptchaService = reCaptchaService;
 }
 public RegistrationFormEventHandler(ReCaptchaService recaptchaService)
 {
     _reCaptchaService = recaptchaService;
 }
Exemplo n.º 26
0
 public UsuarioController(UsuarioService usuarioService, ReCaptchaService reCaptchaService, VagasService vagasService)
 {
     _usuarioService   = usuarioService;
     _reCaptchaService = reCaptchaService;
     _vagasService     = vagasService;
 }
Exemplo n.º 27
0
 public AccountController(AccountService accountService, ReCaptchaService reCaptchaService)
 {
     _accountService   = accountService;
     _reCaptchaService = reCaptchaService;
 }
        public async Task <IHttpActionResult> Register(RegisterViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            // Validate Recaptcha
            var reCaptchaVerfiyUrl = AppSettings.Get <string>("ReCaptchaVerfiyUrl");
            var reCaptchaSecretKey = AppSettings.Get <string>("ReCaptchaSecretKey");

            if (!string.IsNullOrEmpty(reCaptchaVerfiyUrl) && !string.IsNullOrEmpty(reCaptchaSecretKey))
            {
                var remoteIpAddress  = Request.GetOwinContext().Request.RemoteIpAddress;
                var reCaptchaService = new ReCaptchaService(new RestClient(reCaptchaVerfiyUrl));

                var validationResults = reCaptchaService.ValidateResponse(reCaptchaSecretKey, model.ReCaptchaResponse, remoteIpAddress);
                if (validationResults != ReCaptchaValidationResult.Disabled && validationResults != ReCaptchaValidationResult.Success)
                {
                    ModelState.AddModelError("ReCaptchaResponse", new Exception("Unable to validate reCaptcha Response"));
                    return(BadRequest(ModelState));
                }
            }

            // Add User
            var now  = DateTime.UtcNow;
            var user = new ApplicationUser()
            {
                UserName = model.Email, Email = model.Email, EmailConfirmed = false
            };

            user.Organizations.Add(new OrganizationMembership {
                EIN = model.EIN, IsAdmin = true, CreatedAt = now, LastModifiedAt = now, CreatedBy_Id = user.Id, LastModifiedBy_Id = user.Id
            });

            IdentityResult result = await UserManager.CreateAsync(user, model.Password);

            if (!result.Succeeded)
            {
                return(GetErrorResult(result));
            }

            // Add to application role
            result = await UserManager.AddToRoleAsync(user.Id, Roles.Applicant);

            if (!result.Succeeded)
            {
                return(GetErrorResult(result));
            }

            // Send Verification Email
            var nounce = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);

            var queryString = HttpUtility.ParseQueryString(string.Empty);

            queryString["userId"] = user.Id;
            queryString["code"]   = nounce;

            //TODO: Support Urls with existing querystring
            var callbackUrl = $@"{model.EmailVerificationUrl}?{queryString}";

            await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account: " + callbackUrl);

            return(Ok());
        }
Exemplo n.º 29
0
 public void BeforeEachTest()
 {
     server  = new HttpTest();
     captcha = new ReCaptchaService();
 }
Exemplo n.º 30
0
 public RecaptchaVerificator(ReCaptchaService reCaptchaService, IOptions <RecaptchaOptions> recaptchaOptions)
 {
     this.reCaptchaService = reCaptchaService;
     this.recaptchaOptions = recaptchaOptions;
 }