DocSpace-client/web/ASC.Web.Core/Recaptcha.cs

75 lines
2.2 KiB
C#
Raw Normal View History

2021-09-17 14:32:37 +00:00
using System;
using System.IO;
2021-10-25 11:03:14 +00:00
using System.Net.Http;
2021-09-17 14:32:37 +00:00
using System.Security.Authentication;
2021-10-25 11:03:14 +00:00
using System.Text;
using System.Threading.Tasks;
2021-09-17 14:32:37 +00:00
2021-09-17 15:18:34 +00:00
using ASC.Common;
2021-09-17 14:32:37 +00:00
using ASC.Web.Studio.Core;
using Newtonsoft.Json.Linq;
namespace ASC.Web.Core
{
public class RecaptchaException : InvalidCredentialException
{
public RecaptchaException()
{
}
public RecaptchaException(string message)
: base(message)
{
}
}
2021-09-17 15:18:34 +00:00
[Scope]
2021-09-17 14:32:37 +00:00
public class Recaptcha
{
private SetupInfo SetupInfo { get; }
2022-01-13 11:19:39 +00:00
private IHttpClientFactory ClientFactory { get; }
2021-09-17 14:32:37 +00:00
2022-01-13 11:19:39 +00:00
public Recaptcha(SetupInfo setupInfo, IHttpClientFactory clientFactory)
2021-09-17 14:32:37 +00:00
{
SetupInfo = setupInfo;
2022-01-13 11:19:39 +00:00
ClientFactory = clientFactory;
2021-09-17 14:32:37 +00:00
}
public async Task<bool> ValidateRecaptchaAsync(string response, string ip)
2021-09-17 14:32:37 +00:00
{
try
{
2022-01-14 13:12:37 +00:00
var data = $"secret={SetupInfo.RecaptchaPrivateKey}&remoteip={ip}&response={response}";
2021-09-17 14:32:37 +00:00
2021-10-25 11:03:14 +00:00
var request = new HttpRequestMessage();
request.RequestUri = new Uri(SetupInfo.RecaptchaVerifyUrl);
request.Method = HttpMethod.Post;
request.Content = new StringContent(data, Encoding.UTF8, "application/x-www-form-urlencoded");
2021-09-17 14:32:37 +00:00
2022-01-13 11:19:39 +00:00
var httpClient = ClientFactory.CreateClient();
using var httpClientResponse = await httpClient.SendAsync(request);
using (var reader = new StreamReader(await httpClientResponse.Content.ReadAsStreamAsync()))
2021-09-17 14:32:37 +00:00
{
var resp = await reader.ReadToEndAsync();
2021-09-17 14:32:37 +00:00
var resObj = JObject.Parse(resp);
if (resObj["success"] != null && resObj.Value<bool>("success"))
{
return true;
}
if (resObj["error-codes"] != null && resObj["error-codes"].HasValues)
{
return false;
}
}
}
catch (Exception)
{
}
return false;
}
}
}