feat: integrate reCAPTCHA for contact form validation and submission WIP #8
This commit is contained in:
62
Api/Helpers/ReCapthchaAssessment.cs
Normal file
62
Api/Helpers/ReCapthchaAssessment.cs
Normal 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user