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 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 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 { { "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(json); return result?.Success ?? false; } } }