feat: integrate reCAPTCHA for contact form validation and submission WIP #8

This commit is contained in:
Marek Lesko
2025-10-31 15:57:16 +00:00
parent 426b4c55fc
commit 7b22f2d237
5 changed files with 228 additions and 79 deletions

View File

@@ -0,0 +1,62 @@
using System;
using Google.Api.Gax.ResourceNames;
using Google.Cloud.RecaptchaEnterprise.V1;
namespace Api.Helpers
{
public static class ReCaptchaAssessment
{
// Checks the supplied token with Recaptcha Enterprise and returns true if valid.
// Outputs a short reason when false (invalid reason or exception message).
public static bool CheckToken(string token, out string reason, string projectId = "webserverfarm", string recaptchaKey = "6Lf6df0rAAAAAMXcAx1umneXl1QJo9rTrflpWCvB")
{
reason = string.Empty;
if (string.IsNullOrWhiteSpace(token))
{
reason = "empty-token";
return false;
}
try
{
var client = RecaptchaEnterpriseServiceClient.Create();
var request = new CreateAssessmentRequest
{
Parent = $"projects/{projectId}",
Assessment = new Assessment
{
Event = new Event
{
SiteKey = recaptchaKey,
Token = token
}
}
};
var response = client.CreateAssessment(request);
if (response?.TokenProperties == null)
{
reason = "missing-token-properties";
return false;
}
if (!response.TokenProperties.Valid)
{
reason = response.TokenProperties.InvalidReason.ToString();
return false;
}
reason = "valid";
return true;
}
catch (Exception ex)
{
reason = ex.Message;
return false;
}
}
}
}