feat: implement Turnstile verification for enhanced security during login and registration

refactor: remove unnecessary interfaces for services; change user key from UID to UUID
This commit is contained in:
2025-12-31 12:11:09 -05:00
parent 08c4be4f7e
commit 848b8598e5
27 changed files with 579 additions and 84 deletions
@@ -0,0 +1,39 @@
using Microsoft.Extensions.Options;
using SharpbinV3.Server.DTOs;
using SharpbinV3.Server.Settings;
using System.Text.Json;
namespace SharpbinV3.Server.Services.Verification.Providers
{
public sealed class TurnstileVerificationProvider(IOptions<AuthSettings> options, HttpClient httpClient) : IVerificationProvider
{
private readonly AuthSettings _authSettings = options.Value;
private const string SiteverifyUrl = "https://challenges.cloudflare.com/turnstile/v0/siteverify";
public int Priority => 1;
public bool IsConfigured => !string.IsNullOrEmpty(_authSettings.CF_Turnstile_SecretKey) && !string.IsNullOrEmpty(_authSettings.CF_Turnstile_SiteKey);
public async Task<bool> VerifyAsync(string token, string? ip)
{
if (_authSettings.CF_Turnstile_SecretKey is null)
throw new InvalidOperationException("Turnstile secret key is not configured.");
var parameters = new Dictionary<string, string>
{
{ "secret", _authSettings.CF_Turnstile_SecretKey },
{ "response", token }
};
if (!string.IsNullOrEmpty(ip))
parameters.Add("remoteip", ip);
var postContent = new FormUrlEncodedContent(parameters);
var response = await httpClient.PostAsync(SiteverifyUrl, postContent);
response.EnsureSuccessStatusCode();
var json = await response.Content.ReadAsStringAsync();
var result = JsonSerializer.Deserialize<TurnstileResponse>(json);
return result?.Success ?? false;
}
}
}