Files
jdescopingtool/NEW/src/JdeScoping.Client/Services/AuthService.cs
T
Joseph Doherty daaeba2004 refactor(client): replace hardcoded API URLs with ApiRoutes constants
Centralizes all API endpoint strings in ApiRoutes for consistency and
easier maintenance. Adds Hubs class for SignalR endpoints. Removes
completed plan files.
2026-01-28 08:33:48 -05:00

86 lines
2.8 KiB
C#

using System.Net.Http.Json;
using JdeScoping.Client.Auth;
using JdeScoping.Core.ApiContracts;
using JdeScoping.Core.Models.Auth;
namespace JdeScoping.Client.Services;
/// <summary>
/// Handles authentication via encrypted API calls with cookie-based auth.
/// </summary>
public class AuthService : IAuthService
{
private readonly HttpClient _httpClient;
private readonly ICryptoService _cryptoService;
private readonly IAuthStateProvider _authStateProvider;
/// <summary>
/// Initializes a new instance of the <see cref="AuthService"/> class.
/// </summary>
/// <param name="httpClient">The HTTP client for API communication.</param>
/// <param name="cryptoService">The cryptography service.</param>
/// <param name="authStateProvider">The authentication state provider.</param>
public AuthService(
HttpClient httpClient,
ICryptoService cryptoService,
IAuthStateProvider authStateProvider)
{
_httpClient = httpClient;
_cryptoService = cryptoService;
_authStateProvider = authStateProvider;
}
/// <summary>
/// Authenticates a user with encrypted credentials.
/// </summary>
/// <param name="model">The login credentials.</param>
/// <returns>The login result with user information if successful.</returns>
public async Task<LoginResultModel> LoginAsync(LoginModel model)
{
try
{
// Encrypt credentials
var encryptedData = await _cryptoService.EncryptLoginAsync(model);
var request = new EncryptedLoginRequest(encryptedData);
// Send encrypted request
var response = await _httpClient.PostAsJsonAsync(ApiRoutes.Auth.Login, request);
var result = await response.Content.ReadFromJsonAsync<LoginResultModel>();
if (result is null)
{
return new LoginResultModel(false, "Invalid response from server", null);
}
if (result.Success && result.User is not null)
{
// LoginResultModel.User is already UserInfoDto - pass directly
await _authStateProvider.MarkUserAsAuthenticated(result.User);
}
return result;
}
catch (Exception ex)
{
return new LoginResultModel(false, $"Login failed: {ex.Message}", null);
}
}
/// <summary>
/// Logs out the current user and clears authentication state.
/// </summary>
public async Task LogoutAsync()
{
try
{
await _httpClient.PostAsync(ApiRoutes.Auth.Logout, null);
}
catch
{
// Even if logout API fails, clear local state
}
await _authStateProvider.LogoutAsync();
}
}