This commit is contained in:
107
Mod/API/Authentication.cs
Normal file
107
Mod/API/Authentication.cs
Normal file
@ -0,0 +1,107 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ScoreTracker.API
|
||||
{
|
||||
internal class Authentication
|
||||
{
|
||||
private static bool _signedIn = false;
|
||||
private static string _authToken;
|
||||
|
||||
/// <summary>
|
||||
/// Are we signed in?
|
||||
/// </summary>
|
||||
public static bool IsSignedIn()
|
||||
{
|
||||
return _signedIn;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get the steam ticket and user info
|
||||
/// </summary>
|
||||
/// <returns>the steam ticket</returns>
|
||||
private static async Task<string> GetSteamTicket()
|
||||
{
|
||||
Plugin.Log.Info("Getting steam ticket...");
|
||||
return (await new SteamPlatformUserModel().GetUserAuthToken()).token;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Login the user
|
||||
/// </summary>
|
||||
/// <param name="onSuccess">callback for successful login, returns the token</param>
|
||||
/// <param name="onFail">callback for failed login</param>
|
||||
/// <returns>an IEnumerator</returns>
|
||||
public static async Task LoginUser(Action<string> onSuccess, Action<string> onFail)
|
||||
{
|
||||
if (_signedIn && !string.IsNullOrEmpty(_authToken))
|
||||
{
|
||||
onSuccess(_authToken);
|
||||
return;
|
||||
}
|
||||
|
||||
var ticketTask = GetSteamTicket();
|
||||
await Task.Run(() => ticketTask.Wait());
|
||||
|
||||
var ticket = ticketTask.Result;
|
||||
if (string.IsNullOrEmpty(ticket))
|
||||
{
|
||||
Plugin.Log.Error("Login failed :( no steam auth token");
|
||||
onFail("No Steam Auth Token");
|
||||
return;
|
||||
}
|
||||
|
||||
Plugin.Log.Info("Logging in...");
|
||||
var request = await Request.PostJsonAsync($"{Consts.ApiUrl}/auth/login", new Dictionary<object, object> {
|
||||
{ "ticket", ticket }
|
||||
}, false);
|
||||
if (request.IsSuccessStatusCode)
|
||||
{
|
||||
var authToken = request.Headers.GetValues("Authorization").First();
|
||||
Plugin.Log.Info($"Login successful! auth token: {authToken}");
|
||||
|
||||
onSuccess(authToken);
|
||||
_signedIn = true;
|
||||
_authToken = authToken;
|
||||
}
|
||||
else
|
||||
{
|
||||
Plugin.Log.Error($"Login failed! body: {request.StatusCode}");
|
||||
onFail($"Login failed: {request.StatusCode}");
|
||||
|
||||
_signedIn = false;
|
||||
_authToken = null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Validates the auth token and logs out if it's invalid
|
||||
/// </summary>
|
||||
/// <returns>whether the token is valid</returns>
|
||||
public static async Task<bool> ValidateAuthToken()
|
||||
{
|
||||
if (!_signedIn || string.IsNullOrEmpty(_authToken)) // If we're not signed in, return false
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var request = await Request.PostJsonAsync($"{Consts.ApiUrl}/auth/validate", new Dictionary<object, object> {
|
||||
{ "token", _authToken }
|
||||
}, false);
|
||||
|
||||
if (request.IsSuccessStatusCode)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
_signedIn = false;
|
||||
_authToken = null;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
82
Mod/API/Request.cs
Normal file
82
Mod/API/Request.cs
Normal file
@ -0,0 +1,82 @@
|
||||
using Newtonsoft.Json;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Net.Http;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ScoreTracker.API
|
||||
{
|
||||
internal class Request
|
||||
{
|
||||
private static readonly HttpClient client = new HttpClient();
|
||||
|
||||
private class AuthHelper
|
||||
{
|
||||
public bool IsLoggedIn;
|
||||
public string FailReason = "";
|
||||
|
||||
public async Task EnsureLoggedIn()
|
||||
{
|
||||
if (Authentication.IsSignedIn() && await Authentication.ValidateAuthToken())
|
||||
{
|
||||
return; // Already logged in with a valid token
|
||||
}
|
||||
|
||||
await Authentication.LoginUser(
|
||||
token => {
|
||||
IsLoggedIn = true;
|
||||
PersistHeaders(new Dictionary<string, string>
|
||||
{
|
||||
{ "Authorization", $"Bearer {token}" }
|
||||
});
|
||||
},
|
||||
reason =>
|
||||
{
|
||||
FailReason = reason; // Store the reason for failure
|
||||
client.DefaultRequestHeaders.Clear(); // Clear headers
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Persist the given headers for all future requests
|
||||
/// </summary>
|
||||
/// <param name="headers">the headers to persist</param>
|
||||
public static void PersistHeaders(Dictionary<string, string> headers)
|
||||
{
|
||||
client.DefaultRequestHeaders.Clear(); // Clear existing headers
|
||||
foreach (var header in headers)
|
||||
{
|
||||
client.DefaultRequestHeaders.Add(header.Key, header.Value);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Create a POST request to the given URL with the given data
|
||||
/// </summary>
|
||||
/// <param name="url">the url to post to</param>
|
||||
/// <param name="data">the data to post</param>
|
||||
/// <param name="checkAuth">whether to check for authentication</param>
|
||||
/// <returns>the task</returns>
|
||||
public static async Task<HttpResponseMessage> PostJsonAsync(string url, Dictionary<object, object> json, bool checkAuth = true)
|
||||
{
|
||||
if (checkAuth)
|
||||
{
|
||||
var authHelper = new AuthHelper();
|
||||
await authHelper.EnsureLoggedIn();
|
||||
if (!authHelper.IsLoggedIn)
|
||||
{
|
||||
throw new Exception($"Failed to log in: {authHelper.FailReason}");
|
||||
}
|
||||
}
|
||||
var jsonString = JsonConvert.SerializeObject(json, Formatting.None);
|
||||
var content = new StringContent(jsonString, Encoding.UTF8, "application/json");
|
||||
|
||||
// Send the POST request
|
||||
var response = await client.PostAsync(url, content);
|
||||
return response;
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user