64 lines
1.8 KiB
C#
64 lines
1.8 KiB
C#
using System;
|
|
using System.Net.Http;
|
|
using System.Net.Http.Json;
|
|
using System.Text.Json;
|
|
using System.Threading.Tasks;
|
|
using winui_learning_2.Models;
|
|
|
|
namespace winui_learning_2.Services;
|
|
|
|
public class NodplayAuthService
|
|
{
|
|
private static readonly JsonSerializerOptions JsonOptions = new()
|
|
{
|
|
PropertyNameCaseInsensitive = true
|
|
};
|
|
|
|
private readonly HttpClient _httpClient = new()
|
|
{
|
|
BaseAddress = new Uri(ApiConstants.BaseUrl)
|
|
};
|
|
|
|
public async Task<LoginResult> LoginAsync(string username, string password)
|
|
{
|
|
var request = new UserLoginDto
|
|
{
|
|
Username = username,
|
|
Password = password
|
|
};
|
|
|
|
using var response = await _httpClient.PostAsJsonAsync(ApiConstants.LoginPath, request);
|
|
|
|
if (response.IsSuccessStatusCode)
|
|
{
|
|
var body = await response.Content.ReadAsStringAsync();
|
|
|
|
if (string.IsNullOrWhiteSpace(body))
|
|
{
|
|
return LoginResult.Success(username, token: null);
|
|
}
|
|
|
|
var loginResponse = JsonSerializer.Deserialize<LoginResponse>(body, JsonOptions);
|
|
return LoginResult.Success(
|
|
loginResponse?.Username ?? username,
|
|
loginResponse?.GetToken());
|
|
}
|
|
|
|
var errorBody = await response.Content.ReadAsStringAsync();
|
|
var message = string.IsNullOrWhiteSpace(errorBody)
|
|
? $"Login failed ({(int)response.StatusCode})."
|
|
: errorBody;
|
|
|
|
return LoginResult.Failure(message);
|
|
}
|
|
}
|
|
|
|
public readonly record struct LoginResult(bool IsSuccess, string? Username, string? Token, string? ErrorMessage)
|
|
{
|
|
public static LoginResult Success(string username, string? token) =>
|
|
new(true, username, token, null);
|
|
|
|
public static LoginResult Failure(string message) =>
|
|
new(false, null, null, message);
|
|
}
|