using System.Net.Http.Json; namespace FictionArchive.Service.UserService.Services.AuthenticationClient.Authentik; public class AuthentikClient : IAuthenticationServiceClient { private readonly HttpClient _httpClient; private readonly ILogger _logger; public AuthentikClient(HttpClient httpClient, ILogger logger) { _httpClient = httpClient; _logger = logger; } public async Task CreateUserAsync(string username, string email, string displayName) { var request = new AuthentikAddUserRequest { Username = username, Email = email, DisplayName = displayName, IsActive = true }; try { var response = await _httpClient.PostAsJsonAsync("/api/v3/core/users/", request); if (!response.IsSuccessStatusCode) { var errorContent = await response.Content.ReadAsStringAsync(); _logger.LogError( "Failed to create user in Authentik. Status: {StatusCode}, Error: {Error}", response.StatusCode, errorContent); return null; } var userResponse = await response.Content.ReadFromJsonAsync(); _logger.LogInformation("Successfully created user {Username} in Authentik with pk {Pk}", username, userResponse?.Pk); return userResponse; } catch (Exception ex) { _logger.LogError(ex, "Exception while creating user {Username} in Authentik", username); return null; } } public async Task SendRecoveryEmailAsync(int authentikUserId) { try { var response = await _httpClient.PostAsync( $"/api/v3/core/users/{authentikUserId}/recovery_email/", null); if (!response.IsSuccessStatusCode) { var errorContent = await response.Content.ReadAsStringAsync(); _logger.LogError( "Failed to send recovery email for user {UserId}. Status: {StatusCode}, Error: {Error}", authentikUserId, response.StatusCode, errorContent); return false; } _logger.LogInformation("Successfully sent recovery email to Authentik user {UserId}", authentikUserId); return true; } catch (Exception ex) { _logger.LogError(ex, "Exception while sending recovery email to Authentik user {UserId}", authentikUserId); return false; } } }