using System.Text; using adas_core.Application.Repositories.Interfaces; using adas_core.Application.Services.Interfaces; using adas_core.Domain.Models.AppSettings; using adas_core.Domain.Models.MongoModels; using adas_core.Domain.Models.Responses; using adas_core.Domain.Utils; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using MongoDB.Bson; using Newtonsoft.Json; namespace adas_core.Application.Services; public class AuthService : IAuthService { private readonly IAuthorityRepository _authorityRepository; private readonly ILogger _logger; private readonly RecordingSettings _recordingSettings; //private LoginResponse? _loginResponse; public AuthService(IOptions recordingSettings, ILogger logger, IAuthorityRepository authorityRepository) { _recordingSettings = recordingSettings.Value ?? throw new Exception("RecordingSettings must be defined on appSettings"); _logger = logger; _authorityRepository = authorityRepository; _ = InstanceAuthUtils(); } public async Task GetLoginResponse() { try { if (_recordingSettings.RecordingApiUrl.IsEmpty()) { _logger.LogInformation("Url not defined to get token on AuthUtils..."); return null; } var user = new { Username = _recordingSettings.RecordingOrApiClientId, Password = _recordingSettings.RecordingOrApiClientSecret }; var handler = new HttpClientHandler { ServerCertificateCustomValidationCallback = (_, _, _, _) => true }; var client = new HttpClient(handler); var json = JsonConvert.SerializeObject(user); var data = new StringContent(json, Encoding.UTF8, "application/json"); var response = await client.PostAsync($"{_recordingSettings.RecordingApiUrl}/users/login", data); var respToken = response.IsSuccessStatusCode ? await response.Content.ReadAsStringAsync() : null; if (respToken != null) { var ton = JsonConvert.DeserializeObject(respToken); if (ton != null && !ton.Token.IsEmpty()) { AuthUtils.Instance.LoginResponse = ton; return ton; } } return null; } catch (Exception e) { _logger.LogError("Error trying to get token: exception: {eMessage}", e.Message); return null; } } public async Task GetToken() { var loginResponse = AuthUtils.Instance.GetLoginResponse(); if (!loginResponse.Token.IsEmptyOrWhiteSpace() && !loginResponse.IsExpired()) return loginResponse.Token; var resp = await GetLoginResponse(); if (resp != null) return resp.Token; _logger.LogWarning("Failed Getting token check recordingSettings for user and pass"); return ""; } public async Task> GetByUnitId(ObjectId unitId) { return await _authorityRepository.GetByUnitId(unitId); } public async Task> GetUserAuthorities(ObjectId id) { return await _authorityRepository.GetUserAuthorities(id); } public async Task DeleteByUnitId(ObjectId unitId) { return await _authorityRepository.DeleteAllAuthoritiesByUnit(unitId); } public async Task DeleteByDisplayId(ObjectId displayId) { return await _authorityRepository.DeleteAllAuthoritiesByDisplay(displayId); } private async Task InstanceAuthUtils() { if (_recordingSettings.RecordingApiUrl.IsEmpty()) { _logger.LogInformation( "RecordingOrApiUrl not defined on appsettings RecordingSettings AuthUtils not instanciated"); return; } if (AuthUtils.Instance.GetLoginResponse().Token.IsEmpty() || AuthUtils.Instance.GetLoginResponse().IsExpired()) { _logger.LogInformation("Token is not generated or is expired sending request for new token"); var newLoginResponse = await GetLoginResponse(); if (newLoginResponse == null) { _logger.LogError("Token request is null check recordingSettings for user, pass and authorities"); } else { _logger.LogInformation("New Token generated at UTC DATE: {DateTime} exires at: {newLoginResponse}", DateTime.UtcNow, newLoginResponse.Expiration); AuthUtils.Instance.LoginResponse = newLoginResponse; } } } }