C#
97 lines · 3,310 bytes
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
namespace LibreAuth.Sdk
{
public class LibreAuth
{
public string Name { get; set; }
public string OwnerId { get; set; }
public string Version { get; set; }
public string Url { get; set; }
public string SessionId { get; private set; }
public string EncKey { get; private set; }
private static readonly HttpClient Http = new HttpClient();
public LibreAuth(string name, string ownerId, string version, string url)
{
Name = name;
OwnerId = ownerId;
Version = version;
Url = url.TrimEnd('/') + "/";
}
public async Task<JsonDocument> InitAsync(string enckey = null)
{
EncKey = (enckey ?? Guid.NewGuid().ToString("N")).Substring(0, 35);
var res = await ReqAsync(new Dictionary<string, string>
{
["type"] = "init",
["ver"] = Version,
["enckey"] = EncKey,
});
if (!res.RootElement.GetProperty("success").GetBoolean())
throw new Exception(res.RootElement.GetProperty("message").GetString());
SessionId = res.RootElement.GetProperty("sessionid").GetString();
return res;
}
public async Task<JsonElement> LoginAsync(string user, string pass, string hwid = "", string code = "")
{
return await AuthAsync(new Dictionary<string, string>
{
["type"] = "login",
["username"] = user,
["pass"] = pass,
["hwid"] = hwid,
["code"] = code,
});
}
public async Task<JsonElement> LicenseAsync(string key, string hwid = "")
{
return await AuthAsync(new Dictionary<string, string>
{
["type"] = "license",
["key"] = key,
["hwid"] = hwid,
});
}
public async Task<JsonElement> TokenAsync(string token, string hwid = "")
{
return await AuthAsync(new Dictionary<string, string>
{
["type"] = "token",
["token"] = token,
["hwid"] = hwid,
});
}
async Task<JsonElement> AuthAsync(Dictionary<string, string> data)
{
var res = await ReqAsync(data);
if (!res.RootElement.GetProperty("success").GetBoolean())
throw new Exception(res.RootElement.GetProperty("message").GetString());
return res.RootElement.GetProperty("info");
}
async Task<JsonDocument> ReqAsync(Dictionary<string, string> data)
{
data["name"] = Name;
data["ownerid"] = OwnerId;
if (SessionId != null) data["sessionid"] = SessionId;
var content = new FormUrlEncodedContent(data);
var resp = await Http.PostAsync(Url, content);
if ((int)resp.StatusCode == 429) throw new Exception("Rate limited");
var json = await resp.Content.ReadAsStringAsync();
return JsonDocument.Parse(json);
}
}
}