This repository has been archived on 2024-10-29. You can view files and clone it, but cannot push or open issues or pull requests.
beatsaber-scoretracker/Mod/API/Authentication.cs
Liam 7b560075ba
Some checks failed
Deploy API / docker (17, 3.8.5) (push) Failing after 35s
Release Mod / Build (push) Successful in 30s
mod: cleanup auth
2024-08-15 18:22:16 +01:00

146 lines
4.5 KiB
C#

using ScoreTracker.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ScoreTracker.API
{
internal class SigninResponse
{
public bool Success { get; set; }
public string Response { get; set; }
}
internal class Authentication
{
private static bool _signedIn = false;
private static string _authToken;
/// <summary>
/// Validate the auth token and sign in if necessary
/// </summary>
public static async Task<SigninResponse> ValidateAndSignIn()
{
if (_signedIn && await ValidateAuthToken())
{
return new SigninResponse
{
Success = true,
Response = null
}; // Already signed in
}
bool success = false;
string response = null;
await LoginUser(
token => {
success = true;
Request.PersistHeaders(new Dictionary<string, string>
{
{ "Authorization", $"Bearer {token}" }
});
},
reason =>
{
response = reason;
Request.HttpClient.DefaultRequestHeaders.Clear(); // Clear headers
}
);
return new SigninResponse
{
Success = success,
Response = response
};
}
/// <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($"{PluginConfig.Instance.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($"{PluginConfig.Instance.ApiUrl}/auth/validate", new Dictionary<object, object> {
{ "token", _authToken }
}, false);
if (request.IsSuccessStatusCode)
{
return true;
}
else
{
_signedIn = false;
_authToken = null;
return false;
}
}
}
}