/* * Copyright 2024 Ivy Collective * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System.Text; using System.Text.Json; using System.IdentityModel.Tokens.Jwt; using blazingconsole.Types; namespace blazingconsole.Services { public class APIService(SettingsService settingsService) { private readonly HttpClient client = new(); private string? jwt; private bool testsPassed = false; private SettingsService Settings { get; set; } = settingsService; public bool IsReady() { return testsPassed; } public void SetJwt(string jwt) { this.jwt = jwt; testsPassed = false; } // send HTTP requests (yes it's generated by AI) public async Task SendHttpRequest(string path, HttpMethod method, object? body = null) { var request = new HttpRequestMessage(method, $"{Settings.Settings.ApiURL}{path}"); request.Headers.Add("Authorization", $"Bearer {jwt}"); if (body != null) { request.Content = new StringContent(JsonSerializer.Serialize(body), Encoding.UTF8, "application/json"); } var response = await client.SendAsync(request); if (response.IsSuccessStatusCode) { var content = await response.Content.ReadAsStringAsync(); return JsonSerializer.Deserialize(content); } else { return default; } } public LinkedUser? GetLinkedUser() { if (jwt == null) return null; var jwtToken = new JwtSecurityTokenHandler().ReadJwtToken(jwt); return JsonSerializer.Deserialize(jwtToken.Claims.First(x => x.Type == "sub").Value); } public async Task TestAuthorization() { object? response; try { response = await SendHttpRequest("/auth/test", HttpMethod.Get); } catch (Exception ex) { // log error Console.WriteLine(ex.ToString()); response = null; } testsPassed = response != null; return response != null; } } }