-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCaptcha.cs
83 lines (70 loc) · 2.44 KB
/
Captcha.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
using System;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using RestSharp;
namespace VLO_BOARDS
{
public class Captcha
{
public static string ErrorName = "CaptchaError";
public static string ErrorStatus = "Bad captcha";
public static readonly float Threshold = 0.7f;
private readonly IHttpClientFactory _clientFactory;
private readonly CaptchaCredentials _credentials;
private static readonly Regex AnRegex = new ("^[0-9a-zA-Z_-]*$");
public Captcha(IHttpClientFactory clientFactory, CaptchaCredentials credentials)
{
_clientFactory = clientFactory;
_credentials = credentials;
}
/// <summary>
/// Verifies google recaptcha v3 response
/// </summary>
/// <param name="response"> Recaptcha response </param>
/// <returns> User score </returns>
/// <exception cref="ArgumentException"></exception>
public async Task<float> VerifyCaptcha(string response)
{
if (!AnRegex.IsMatch(response))
{
throw new ArgumentException("Invalid response str");
}
var client = new RestClient("https://www.google.com/recaptcha/api/");
var req = new RestRequest("siteverify");
req.AddParameter("secret", _credentials.PrivateKey);
req.AddParameter("response", response);
var res = await client.ExecutePostAsync<GoogleResponse>(req);
var googleRes = res.Data;
if (googleRes is null)
{
return -1;
}
return googleRes.score;
}
}
public class CaptchaApiParams
{
public string secret;
public string response;
}
public class CaptchaCredentials
{
public readonly string PrivateKey;
public readonly string PublicKey;
public CaptchaCredentials(string privateKey, string publicKey)
{
this.PrivateKey = privateKey;
this.PublicKey = publicKey;
}
}
public class GoogleResponse
{
public bool success { get; set; }
public DateTime challenge_ts { get; set; }
public string hostname { get; set; }
public float score { get; set; }
}
}