2023-04-14 13:25:56 -04:00
|
|
|
|
using Bit.Core.Auth.Models.Api;
|
|
|
|
|
|
using Bit.Core.Auth.Services;
|
|
|
|
|
|
using Bit.Core.Context;
|
2021-07-22 12:29:06 -05:00
|
|
|
|
using Bit.Core.Exceptions;
|
|
|
|
|
|
using Microsoft.AspNetCore.Mvc.Filters;
|
|
|
|
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
|
|
|
|
|
2023-04-14 13:25:56 -04:00
|
|
|
|
namespace Bit.Core.Auth.Utilities;
|
2022-08-29 16:06:55 -04:00
|
|
|
|
|
2021-07-22 12:29:06 -05:00
|
|
|
|
public class CaptchaProtectedAttribute : ActionFilterAttribute
|
|
|
|
|
|
{
|
|
|
|
|
|
public string ModelParameterName { get; set; } = "model";
|
2022-08-29 16:06:55 -04:00
|
|
|
|
|
2021-07-22 12:29:06 -05:00
|
|
|
|
public override void OnActionExecuting(ActionExecutingContext context)
|
|
|
|
|
|
{
|
|
|
|
|
|
var currentContext = context.HttpContext.RequestServices.GetRequiredService<ICurrentContext>();
|
|
|
|
|
|
var captchaValidationService = context.HttpContext.RequestServices.GetRequiredService<ICaptchaValidationService>();
|
|
|
|
|
|
|
|
|
|
|
|
if (captchaValidationService.RequireCaptchaValidation(currentContext, null))
|
|
|
|
|
|
{
|
|
|
|
|
|
var captchaResponse = (context.ActionArguments[ModelParameterName] as ICaptchaProtectedModel)?.CaptchaResponse;
|
|
|
|
|
|
|
2022-05-09 12:25:13 -04:00
|
|
|
|
if (string.IsNullOrWhiteSpace(captchaResponse))
|
2021-07-22 12:29:06 -05:00
|
|
|
|
{
|
|
|
|
|
|
throw new BadRequestException(captchaValidationService.SiteKeyResponseKeyName, captchaValidationService.SiteKey);
|
2022-08-29 15:53:48 -04:00
|
|
|
|
}
|
|
|
|
|
|
|
2022-05-09 12:25:13 -04:00
|
|
|
|
var captchaValidationResponse = captchaValidationService.ValidateCaptchaResponseAsync(captchaResponse,
|
|
|
|
|
|
currentContext.IpAddress, null).GetAwaiter().GetResult();
|
|
|
|
|
|
if (!captchaValidationResponse.Success || captchaValidationResponse.IsBot)
|
2021-07-22 12:29:06 -05:00
|
|
|
|
{
|
|
|
|
|
|
throw new BadRequestException("Captcha is invalid. Please refresh and try again");
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|