using System.Net.Http.Json; using JdeScoping.Client.Auth; using JdeScoping.Core.ApiContracts; using JdeScoping.Core.Models.Auth; namespace JdeScoping.Client.Services; /// /// Handles authentication via encrypted API calls with cookie-based auth. /// public class AuthService : IAuthService { private readonly HttpClient _httpClient; private readonly ICryptoService _cryptoService; private readonly IAuthStateProvider _authStateProvider; /// /// Initializes a new instance of the class. /// /// The HTTP client for API communication. /// The cryptography service. /// The authentication state provider. public AuthService( HttpClient httpClient, ICryptoService cryptoService, IAuthStateProvider authStateProvider) { _httpClient = httpClient; _cryptoService = cryptoService; _authStateProvider = authStateProvider; } /// /// Authenticates a user with encrypted credentials. /// /// The login credentials. /// The login result with user information if successful. public async Task 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(); 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); } } /// /// Logs out the current user and clears authentication state. /// public async Task LogoutAsync() { try { await _httpClient.PostAsync(ApiRoutes.Auth.Logout, null); } catch { // Even if logout API fails, clear local state } await _authStateProvider.LogoutAsync(); } }