Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added plain ValidationAttribute for model-based validation #84

Merged
merged 1 commit into from
Dec 18, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions reCAPTCHA.AspNetCore.Example/Controllers/SomeAPIControlelr.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
using Microsoft.AspNetCore.Mvc;
using reCAPTCHA.AspNetCore.Attributes;
using reCAPTCHA.AspNetCore.Example.Models;
using System.ComponentModel.DataAnnotations;

namespace reCAPTCHA.AspNetCore.Example.Controllers
{
[ApiController]
public class SomeApiController : Controller
{
[HttpGet]
public ActionResult SomeAction(string someValue, [Required, RecaptchaResponse] string reCaptchaResponseCode)
{
return Ok($"I have done something with {someValue} after reCaptcha was validated");
}

[HttpPost]
public ActionResult SomeAction(OtherModel model)
{
return Ok($"I have done something after reCaptcha was validated");
}
}
}
10 changes: 10 additions & 0 deletions reCAPTCHA.AspNetCore.Example/Models/OtherModel.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
using reCAPTCHA.AspNetCore.Attributes;

namespace reCAPTCHA.AspNetCore.Example.Models
{
public class OtherModel
{
[RecaptchaResponse(MinimumScore = 0.5)]
public string ReCaptchaResponseCode { get; set; }
}
}
62 changes: 62 additions & 0 deletions reCAPTCHA.AspNetCore/Attributes/RecaptchaResponseAttribute.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
using System;
using System.ComponentModel.DataAnnotations;
using System.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace reCAPTCHA.AspNetCore.Attributes
{
/// <summary>
/// Validates reCaptcha response code bound to a property, parameter or field.
/// </summary>
/// <seealso cref="ValidationAttribute" />
/// <seealso cref="IRecaptchaService.Validate(string)"/>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Field)]
public class RecaptchaResponseAttribute : ValidationAttribute
{
/// <summary>
/// Gets a value that indicates whether the attribute requires validation context.
/// </summary>
public override bool RequiresValidationContext => true;

/// <summary>
/// Gets or sets the minimum score.
/// </summary>
/// <value>
/// The minimum score.
/// </value>
/// <seealso cref="ValidateRecaptchaAttribute._minimumScore"/>
public double MinimumScore { get; set; }

/// <summary>
/// Returns wether the captcha validation was deemed successful based on the value of a member to attribute has been applied to.
/// </summary>
/// <param name="value">The value to validate.</param>
/// <param name="validationContext">The context information about the validation operation.</param>
/// <returns>
/// An instance of the <see cref="System.ComponentModel.DataAnnotations.ValidationResult" /> class.
/// </returns>
/// <exception cref="ConfigurationErrorsException">When reCaptcha has not been configured.</exception>
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (!(value is string responseCode)
|| string.IsNullOrWhiteSpace(responseCode))
return null;

var validationservice = validationContext.GetService<IRecaptchaService>();

if(validationservice is null)
throw new ConfigurationErrorsException($"{typeof(IRecaptchaService).Assembly.GetName().Name} has not been configured");

var response = validationservice.Validate(responseCode).Result;

if (response.success
&& (response.score == 0 || response.score >= MinimumScore))

return ValidationResult.Success;

else

return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace reCAPTCHA.AspNetCore.Attributes
{

/// <summary>
/// Validates Recaptcha submitted by a form using: @Html.Recaptcha(RecaptchaSettings.Value)
/// </summary>
Expand Down
4 changes: 4 additions & 0 deletions reCAPTCHA.AspNetCore/reCAPTCHA.AspNetCore.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -58,4 +58,8 @@
<PackagePath></PackagePath>
</None>
</ItemGroup>

<ItemGroup>
<PackageReference Include="System.Configuration.ConfigurationManager" Version="5.0.0" />
</ItemGroup>
</Project>