public ValidateRecaptchaFilter(IRecaptchaService recaptchaService, IOptionsMonitor <RecaptchaOptions> options,
                                ILogger <ValidateRecaptchaFilter> logger)
 {
     _recaptchaService = recaptchaService;
     _logger           = logger;
     _options          = options.CurrentValue;
 }
        private void HandleBadResult(ActionExecutingContext context, RecaptchaOptions recaptchaOptions,
                                     CheckResult result, RecaptchaServiceException re, Exception e)
        {
            var           options      = recaptchaOptions.AttributeOptions;
            IActionResult handleResult = null;

            if (re != null)
            {
                handleResult = options.OnRecaptchaServiceException?.Invoke(context, _action, result, re);
            }
            else if (e != null)
            {
                handleResult = options.OnException?.Invoke(context, _action, result, e);
            }
            else if (result != null)
            {
                handleResult = options.OnVerificationFailed?.Invoke(context, _action, result);
            }

            if (options.OnReturnBadRequest != null)
            {
                handleResult = options.OnReturnBadRequest?.Invoke(context, _action, result, re, e);
            }

            context.Result = handleResult ?? new BadRequestObjectResult(recaptchaOptions.VerificationFailedMessage);
        }
Beispiel #3
0
 public InfoController(IServiceProvider services, ILinkGenerator link, IOptionsSnapshot <RecaptchaOptions> recaptchaOptions, IDiscordOAuthHandler discordOAuth, IScraperService scrapers)
 {
     _services         = services;
     _link             = link;
     _discordOAuth     = discordOAuth;
     _scrapers         = scrapers;
     _recaptchaOptions = recaptchaOptions.Value;
 }
        public static void ConfigureRecaptcha(this IServiceCollection services, RecaptchaOptions recaptchaOptions)
        {
            services.Configure <RecaptchaOptions>(co =>
            {
                co.SecretKey = recaptchaOptions.SecretKey;
            });

            services.ConfigureService();
        }
        public void InjectRecaptcha(Page page, Control target, RecaptchaOptions options)
        {
            if (options.Enabled == false)
            {
                return;
            }

            var control = target as HtmlControl;

            if (control == null)
            {
                throw new ArgumentException("Control argument cannot be null.", nameof(target));
            }

            if (control.HasControls())
            {
                foreach (HtmlControl cntrl in control.Controls)
                {
                    if (cntrl.HasControls() == false &&
                        cntrl.TagName.Equals(HtmlTextWriterTag.Div.ToString(), StringComparison.OrdinalIgnoreCase))
                    {
                        control = cntrl;
                        break;
                    }
                }
            }

            control.Attributes.Add("class", RecaptchaConstants.DefaultElementCssClass);

            var json  = options.SerializeToJson();
            var items = JsonConvert.DeserializeObject <IDictionary <string, string> >(json);

            foreach (var item in items)
            {
                control.Attributes.Add($"data-{item.Key}", item.Value);
            }

            AddLoadingScript(page);

            var script =
                @"(function ($) {
                    var container = '" + control.ClientID + @"';
                    var payload = '" + json + @"';

                    netFORUM.onPageLoad(function () {
		                netFORUM.reCAPTCHA.renderRecaptcha(container, payload);
                        $('[data-invoke-recaptcha], .invoke-recaptcha').each(function (index, elem) {
                            netFORUM.reCAPTCHA.wireRecaptchaChallenge(elem);
                        });
	                });
                })(typeof(jQuery) !== 'undefined' ? jQuery : null);";

            page.ClientScript.RegisterStartupScript(GetType(), GetType().Namespace, script, true);

            AddRecaptchaScript(page, true);
        }
Beispiel #6
0
 public HomeController(IHubspotService hubspotService,
                       IRecaptchaService recaptchaService,
                       IOptionsMonitor <RecaptchaOptions> options,
                       ILogger <HomeController> logger
                       ) : base()
 {
     _hubspotService   = hubspotService;
     _recaptchaService = recaptchaService;
     _options          = options.CurrentValue;
     _logger           = logger;
 }
        /// <summary>
        ///
        /// </summary>
        /// <param name="settings"></param>
        /// <param name="options"></param>
        public RecaptchaTagHelper(IOptionsMonitor <RecaptchaSettings> settings, IOptionsMonitor <RecaptchaOptions> options)
        {
            _ = settings ?? throw new ArgumentNullException(nameof(settings));
            _ = options ?? throw new ArgumentNullException(nameof(options));

            _settings = settings.CurrentValue;
            _options  = options.CurrentValue;

            Theme = _options.Theme;
            Size  = _options.Size;
        }
Beispiel #8
0
        public RecaptchaValidator(
            IOptions <RecaptchaOptions> optionsAccessor
            )
        {
            HttpClient = new HttpClient(new HttpClientHandler())
            {
                Timeout = TimeSpan.FromSeconds(3)
            };

            Options = optionsAccessor.Value;
        }
Beispiel #9
0
 /// <summary>
 /// Initializes a new instance of the <see cref="API"/> class.
 /// </summary>
 /// <param name="hubspotService">DI for <see cref="HubspotService"/>.</param>
 /// <param name="recaptchaService">DI for <see cref="RecaptchaService"/>.</param>
 /// <param name="recaptchaOptions">DI for <see cref="RecaptchaOptions"/>.</param>
 /// <param name="logger">DI for <see cref="ILogger"/>.</param>
 public API(
     IHubspotService hubspotService,
     IRecaptchaService recaptchaService,
     IOptionsMonitor <RecaptchaOptions> recaptchaOptions,
     ILogger <APILoggingCategory> logger)
 {
     this.hubspotService   = hubspotService;
     this.recaptchaService = recaptchaService;
     this.recaptchaOptions = recaptchaOptions.CurrentValue;
     this.logger           = logger;
 }
        /// <summary>
        ///
        /// </summary>
        /// <param name="settings"></param>
        /// <param name="options"></param>
        /// <param name="tagHelperComponentManager"></param>
        /// <exception cref="ArgumentNullException"></exception>
        public RecaptchaInvisibleTagHelper(IOptionsMonitor <RecaptchaSettings> settings, IOptionsMonitor <RecaptchaOptions> options,
                                           ITagHelperComponentManager tagHelperComponentManager)
        {
            _ = settings ?? throw new ArgumentNullException(nameof(settings));
            _ = options ?? throw new ArgumentNullException(nameof(options));
            _ = tagHelperComponentManager ?? throw new ArgumentNullException(nameof(tagHelperComponentManager));

            _settings = settings.CurrentValue;
            _options  = options.CurrentValue;
            _tagHelperComponentManager = tagHelperComponentManager;

            Badge = _options.Badge;
        }
        public void ValidationFailedAction_ShouldNeverReturn_ValidationFailedActionUnspecified()
        {
            // Arrange
            var optionsUnmodified = new RecaptchaOptions();
            var optionsModified   = new RecaptchaOptions();

            // Act
            optionsModified.ValidationFailedAction = ValidationFailedAction.Unspecified;

            // Assert
            Assert.AreNotEqual(ValidationFailedAction.Unspecified, optionsUnmodified.ValidationFailedAction);
            Assert.AreNotEqual(ValidationFailedAction.Unspecified, optionsModified.ValidationFailedAction);
        }
Beispiel #12
0
        /// <summary>
        /// Configures <see cref="RecaptchaService"/> for usage with dependency injection.
        /// </summary>
        /// <param name="services">The <see cref="IServiceCollection"/> to add services.</param>
        /// <param name="recaptchaOptions">Recaptcha service options.</param>
        /// <param name="configuration">Delegate for configuring options <see cref="RecaptchaOptions"/>.</param>
        public static void ConfigureRecaptcha(this IServiceCollection services, RecaptchaOptions recaptchaOptions,
                                              Action <RecaptchaOptions> configuration = null)
        {
            configuration?.Invoke(recaptchaOptions);

            services.Configure <RecaptchaOptions>(co =>
            {
                co.SecretKey              = recaptchaOptions.SecretKey;
                co.ScoreThreshold         = recaptchaOptions.ScoreThreshold;
                co.ActionsScoreThresholds = recaptchaOptions.ActionsScoreThresholds;
            });

            services.ConfigureService();
        }
Beispiel #13
0
 public static bool IsSet(this RecaptchaOptions options, RecaptchaOptions option)
 {
     return((options & option) != 0);
 }
Beispiel #14
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseSqlServer(
                                                             Configuration.GetConnectionString("DefaultConnection")));

            //03-12-18 added support for Roles
            services.AddDefaultIdentity <IdentityUser>()     //https://github.com/aspnet/Identity/issues/1884
            .AddRoles <IdentityRole>()
            .AddEntityFrameworkStores <ApplicationDbContext>();

            //services.AddIdentity<IdentityUser, IdentityRole>()
            //        .AddEntityFrameworkStores<ApplicationDbContext>()
            //        .AddDefaultTokenProviders();

            services.AddAuthentication()
            .AddMicrosoftAccount(microsoftOptions =>
            {
                microsoftOptions.ClientId     = Configuration["Authentication:Microsoft:ClientId"];
                microsoftOptions.ClientSecret = Configuration["Authentication:Microsoft:ClientSecret"];
            })
            .AddGoogle(googleOptions =>
            {
                googleOptions.ClientId     = Configuration["Authentication:Google:ClientId"];
                googleOptions.ClientSecret = Configuration["Authentication:Google:ClientSecret"];
            });

            services.Configure <IdentityOptions>(options =>
            {
                // Password settings.
                options.Password.RequireDigit           = true;
                options.Password.RequireLowercase       = true;
                options.Password.RequireNonAlphanumeric = false;        //was true
                options.Password.RequireUppercase       = true;
                options.Password.RequiredLength         = 6;
                options.Password.RequiredUniqueChars    = 1;

                // Lockout settings.
                options.Lockout.DefaultLockoutTimeSpan  = TimeSpan.FromMinutes(5);
                options.Lockout.MaxFailedAccessAttempts = 5;
                options.Lockout.AllowedForNewUsers      = true;

                // User settings.
                options.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
                options.User.RequireUniqueEmail        = true;          //was false

                options.SignIn.RequireConfirmedEmail = true;            //added
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddSingleton <IEmailSender, EmailSender>();
            services.Configure <ServiceConfig>(Configuration.GetSection("ServiceConfig"));

            var recapt = new RecaptchaOptions
            {
                SiteKey   = Configuration["ServiceConfig:ReCaptchaSiteKey"] ?? "MissingRecaptchaSiteKey",
                SecretKey = Configuration["ServiceConfig:ReCaptchaSecretKey"] ?? "MissingRecaptchaSecretKey"
            };

            services.AddRecaptcha(recapt);
        }
Beispiel #15
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            MxReturnCode <bool> rc = new MxReturnCode <bool>($"{Startup.WebAppName} v{Startup.WebAppVersion}");

            rc.Init(Assembly.GetExecutingAssembly(), "*****@*****.**", null,
                    Configuration?.GetConnectionString("AzureWebJobsServiceBus"), Configuration?["MxLogMsg:AzureServiceBusQueueName"], MxMsgs.SupportedCultures);

            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
                options.ConsentCookie         = new CookieBuilder
                {
                    Name        = PrivacyModel.ConsentCookieName,
                    Expiration  = new TimeSpan(PrivacyModel.ConsentCookieExpiryDays, 0, 0, 0),
                    IsEssential = true
                };  //ConsentCookie needs to be marked essential - see support 119030623000476 https://docs.microsoft.com/en-us/aspnet/core/security/gdpr?view=aspnetcore-2.2
            });

            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseSqlServer(
                                                             Configuration.GetConnectionString("DefaultConnection")));
            services.AddDefaultIdentity <IdentityUser>()
            .AddRoles <IdentityRole>()                      //add support for roles - https://github.com/aspnet/Identity/issues/1884
            .AddDefaultUI(UIFramework.Bootstrap4)
            .AddEntityFrameworkStores <ApplicationDbContext>();

            services.Configure <IdentityOptions>(options =>
            {
                // Password settings.
                options.Password.RequireDigit           = true;
                options.Password.RequireLowercase       = true;
                options.Password.RequireNonAlphanumeric = false; //was true
                options.Password.RequireUppercase       = true;
                options.Password.RequiredLength         = 6;
                options.Password.RequiredUniqueChars    = 1;

                // Lockout settings.
                options.Lockout.DefaultLockoutTimeSpan  = TimeSpan.FromMinutes(5);
                options.Lockout.MaxFailedAccessAttempts = 5;
                options.Lockout.AllowedForNewUsers      = true;

                // User settings.
                options.User.AllowedUserNameCharacters = MxIdentityCommon.EmailAllowedChars;
                //at registration must allow same characters as for email, but when changing username restrict
                //to MxIdentityCommon.NewUsernameAllowedChars - "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
                options.User.RequireUniqueEmail      = true; //was false
                options.SignIn.RequireConfirmedEmail = true; //added
            });

            services.AddAuthentication()
            .AddMicrosoftAccount(microsoftOptions =>
            {
                microsoftOptions.ClientId     = Configuration["Authentication:Microsoft:ClientId"];
                microsoftOptions.ClientSecret = Configuration["Authentication:Microsoft:ClientSecret"];
            })
            .AddGoogle(googleOptions =>
            {
                googleOptions.ClientId     = Configuration["Authentication:Google:ClientId"];
                googleOptions.ClientSecret = Configuration["Authentication:Google:ClientSecret"];
            });

            services.AddMvc(options =>
            {
                options.SslPort = _isDevelopment ? 44357 : 443;
                options.Filters.Add(new RequireHttpsAttribute());
            }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            services.AddScoped <IMxIdentitySeedDb, MxIdentitySeedDb>();

            services.AddSingleton <IEmailSender, EmailSender>();
            services.Configure <ServiceConfig>(Configuration.GetSection("ServiceConfig"));

            var recapt = new RecaptchaOptions
            {
                SiteKey   = Configuration["ServiceConfig:reCaptchaSiteKey"] ?? "MissingRecaptchaSiteKey",
                SecretKey = Configuration["ServiceConfig:reCaptchaSecretKey"] ?? "MissingRecaptchaSecretKey"
            };

            services.AddRecaptcha(recapt);
        }
Beispiel #16
0
 public RecaptchaTagHelper(IOptions <RecaptchaOptions> recaptchaOptions)
 {
     _recaptchaOptions = recaptchaOptions.Value;
 }
Beispiel #17
0
 public PersonController(IRecaptchaService recaptcha, IOptions <RecaptchaOptions> recaptchaOptions)
 {
     this.recaptcha        = recaptcha as RecaptchaService;
     this.recaptchaOptions = recaptchaOptions.Value;
 }
 public RecaptchaVerifier(IHttpClientFactory httpClientFactory, IOptions <RecaptchaOptions> options)
 {
     _httpClientFactory = httpClientFactory;
     _options           = options.Value;
 }
Beispiel #19
0
 public RecaptchaSettings(string siteKey, string siteSecret, RecaptchaOptions options = RecaptchaOptions.None)
 {
     SiteKey    = siteKey;
     SiteSecret = siteSecret;
     Options    = options;
 }
Beispiel #20
0
 public RecaptchaSettings(string siteKey, string siteSecret, RecaptchaOptions options = RecaptchaOptions.None)
 {
     SiteKey = siteKey;
       SiteSecret = siteSecret;
       Options = options;
 }
Beispiel #21
0
 public static bool IsSet(this RecaptchaOptions options, RecaptchaOptions option)
 {
     return (options & option) != 0;
 }
Beispiel #22
0
 /// <summary>
 /// Recaptcha service constructor.
 /// </summary>
 /// <param name="recaptchaOptions">Recaptcha options.</param>
 /// <param name="recaptchaClient">Recaptcha Refit client.</param>
 public RecaptchaService(IOptions <RecaptchaOptions> recaptchaOptions, IRecaptchaClient recaptchaClient)
 {
     _recaptchaOptions = recaptchaOptions?.Value;
     _recaptchaClient  = recaptchaClient;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="RecaptchaService"/> class.
 /// </summary>
 /// <param name="clientFactory">DI for <see cref="IHttpClientFactory"/>.</param>
 /// <param name="options">DI for <see cref="RecaptchaOptions"/>.</param>
 public RecaptchaService(IHttpClientFactory clientFactory, IOptionsMonitor <RecaptchaOptions> options)
 {
     this.options       = options.CurrentValue;
     this.clientFactory = clientFactory;
 }