SessionZero/SessionZeroClient/sessionzero/Assets/Scripts/API/ApiHandler.cs
2025-03-28 14:59:47 -05:00

145 lines
4.6 KiB
C#

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Godot;
using HttpClient = System.Net.Http.HttpClient;
namespace SessionZeroClient.API;
public class ApiHandler : IApiHandler
{
private readonly HttpClient _httpClient;
public ApiHandler()
{
var handler = new HttpClientHandler
{
UseDefaultCredentials = true,
};
_httpClient = new HttpClient(handler)
{
Timeout = TimeSpan.FromSeconds(5),
};
}
/// <summary>
/// Returns true if the server URL is reachable valid, false otherwise.
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public async Task<bool> ValidateServerUrl(string url)
{
try
{
var apiString = $"{url}/api/Database/validate-server";
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
var response = await _httpClient.GetAsync(apiString, cts.Token);
if (!response.IsSuccessStatusCode)
{
return false;
}
var responseString = await response.Content.ReadAsStringAsync(cts.Token);
var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
var validationResponse = JsonSerializer.Deserialize<ServerUrlValidationResponse>(responseString, options);
return validationResponse?.IsValid ?? false;
}
catch
{
throw new HttpRequestException($"Server {url} is invalid or not reachable.");
return false;
}
}
/// <summary>
/// Register a new user with the server.
/// </summary>
/// <param name="url"></param>
/// <param name="username"></param>
/// <param name="email"></param>
/// <param name="password"></param>
/// <returns></returns>
/// <exception cref="HttpRequestException"></exception>
public async Task<string> Register(string url, string username, string email, string password)
{
bool isValidServer = await ValidateServerUrl(url);
if (!isValidServer)
{
throw new HttpRequestException($"Could not Register User, Server {url} is invalid or not reachable.");
}
var apiString = $"{url}/api/Auth/register";
var requestBody = new Dictionary<string, string>
{
{"username", username},
{"email", email},
{"password", password}
};
var jsonBody = JsonSerializer.Serialize(requestBody);
var content = new StringContent(jsonBody, System.Text.Encoding.UTF8, "application/json");
var response = await _httpClient.PostAsync(apiString, content);
if (!response.IsSuccessStatusCode)
{
throw new HttpRequestException($"Register failed: {response.StatusCode}");
}
var responseString = await response.Content.ReadAsStringAsync();
return responseString;
}
/// <summary>
/// Login to the server with the given username and password. Returns the JWT token if successful.
/// </summary>
/// <param name="url"></param>
/// <param name="username"></param>
/// <param name="password"></param>
/// <returns></returns>
/// <exception cref="HttpRequestException"></exception>
public async Task<string> Login(string url, string username, string password)
{
bool isValidServer = await ValidateServerUrl(url);
if (!isValidServer)
{
throw new HttpRequestException($"Could not Login, Server {url} is invalid or not reachable.");
}
var apiString = $"{url}/api/Auth/login";
var requestBody = new Dictionary<string, string>
{
{"username", username},
{"password", password}
};
var jsonBody = JsonSerializer.Serialize(requestBody);
var content = new StringContent(jsonBody, System.Text.Encoding.UTF8, "application/json");
var response = await _httpClient.PostAsync(apiString, content);
if (!response.IsSuccessStatusCode)
{
throw new HttpRequestException($"Login failed: {response.StatusCode}");
}
var responseString = await response.Content.ReadAsStringAsync();
return responseString;
}
public class ServerUrlValidationResponse
{
public bool IsValid { get; set; }
public string Message { get; set; }
}
}