| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174 |
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.AspNetCore.Mvc.Diagnostics;
- using Microsoft.Extensions.Caching.Memory;
- using System.Net;
-
- namespace Diligent.WebAPI.Business.Services
- {
- public class ScreeningTestService : IScreeningTestService
- {
- private readonly ScreeningTestSettings _settings;
- private readonly ILogger<ScreeningTestService> _logger;
- private readonly IMemoryCache _memoryCache;
-
- public ScreeningTestService(IOptions<ScreeningTestSettings> settings, ILogger<ScreeningTestService> logger, IMemoryCache memoryCache)
- {
- _settings = settings.Value;
- _logger = logger;
- _memoryCache = memoryCache;
- }
- public async Task<BaseResult<IEnumerable<TestMicroserviceRequest>>> GetScreening()
- {
- string token = await GetToken();
- _logger.LogInformation($"Start calling microservice to get tests request");
- var httpClient = new HttpClient();
- var request = new HttpRequestMessage(HttpMethod.Get, _settings.Url + "tests");
- request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
-
- _logger.LogInformation("Initilazing http call to microservice");
- HttpResponseMessage httpResponseMessage;
- try
- {
- _logger.LogInformation("Calling microservis to get test");
- httpResponseMessage = httpClient.SendAsync(request).Result;
- }
- catch (Exception ex)
- {
- _logger.LogError($"Error in call: {ex.Message}");
- return new BaseResult<IEnumerable<TestMicroserviceRequest>>
- {
- IsSuccess = false,
- DataObject = new List<TestMicroserviceRequest>()
- };
- }
-
- if (httpResponseMessage.StatusCode == HttpStatusCode.Unauthorized)
- {
- _logger.LogError("Error: Unauthorized");
- return new BaseResult<IEnumerable<TestMicroserviceRequest>>
- {
- IsSuccess = false,
- DataObject = new List<TestMicroserviceRequest>()
- };
- }
-
- if (httpResponseMessage.StatusCode != HttpStatusCode.OK)
- {
- _logger.LogError("Error");
- return new BaseResult<IEnumerable<TestMicroserviceRequest>>
- {
- IsSuccess = false,
- DataObject = new List<TestMicroserviceRequest>()
- };
- }
-
- var response = httpResponseMessage.Content.ReadAsStringAsync().Result;
- var resultData = JsonConvert.DeserializeObject<IEnumerable<TestMicroserviceRequest>>(response);
- _logger.LogInformation($"Call pass and it received: {resultData.Count()} records");
- return new BaseResult<IEnumerable<TestMicroserviceRequest>>
- {
- DataObject = resultData
- };
-
- }
-
- private async Task<string> GetToken()
- {
- string token = "";
- if (_memoryCache.TryGetValue("JWT", out string t) && !string.IsNullOrEmpty(t))
- {
- token = t;
- }
- else
- {
- var result = await LoginToScreening();
- var cacheEntryOptions = new MemoryCacheEntryOptions()
- .SetSlidingExpiration(TimeSpan.FromSeconds(60))
- .SetAbsoluteExpiration(TimeSpan.FromSeconds(3600))
- .SetPriority(CacheItemPriority.Normal)
- .SetSize(1024);
- _memoryCache.Set("JWT", result.Token, cacheEntryOptions);
- token = result.Token;
- }
-
- return token;
- }
-
- public async Task<AuthSuccessResponse> LoginToScreening()
- {
- _logger.LogInformation($"Start calling microservice to login on service {string.Format(_settings.Url + "auth")}");
- var httpClient = new HttpClient();
- var requestUri = new Uri(string.Format(_settings.Url + "auth"));
- var httpContent = new StringContent(System.Text.Json.JsonSerializer.Serialize(new AuthMicroserviceRequest
- {
- Email = _settings.Email,
- Password = _settings.Password
- }),
- Encoding.UTF8,
- "application/json");
- var response = await httpClient.PostAsync(requestUri, httpContent);
- var content = await response.Content.ReadAsStringAsync();
- try
- {
- var result = JsonConvert.DeserializeObject<AuthSuccessResponse>(content);
- var expires = result.Expires.Value - DateTime.UtcNow;
- var cacheEntryOptions = new MemoryCacheEntryOptions()
- .SetSlidingExpiration(TimeSpan.FromSeconds(60))
- .SetAbsoluteExpiration(expires)
- .SetPriority(CacheItemPriority.Normal)
- .SetSize(1024);
- _memoryCache.Set("JWT", result.Token, cacheEntryOptions);
- _logger.LogInformation($"Call pass and it received: {result}");
-
- return result;
- }
- catch (Exception ex)
- {
- _logger.LogInformation($"Error in call: ");
- return new AuthSuccessResponse { Token = "" };
- }
- }
-
- public async Task<bool> SendTest(TestMicroserviceInviteRequest test)
- {
- string token = await GetToken();
- _logger.LogInformation($"Start calling microservice to send test request");
- var httpClient = new HttpClient();
- var request = new HttpRequestMessage(HttpMethod.Post, _settings.Url + "tests");
- request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
- var httpContent = new StringContent(System.Text.Json.JsonSerializer.Serialize(test),
- Encoding.UTF8,
- "application/json");
- request.Content = httpContent;
-
-
- _logger.LogInformation("Initilazing http call to microservice");
- HttpResponseMessage httpResponseMessage;
- try
- {
- _logger.LogInformation("Calling microservis to send test");
- httpResponseMessage = httpClient.SendAsync(request).Result;
- }
- catch (Exception ex)
- {
- _logger.LogError($"Error in call: {ex.Message}");
- return false;
- }
-
- if (httpResponseMessage.StatusCode == HttpStatusCode.Unauthorized)
- {
- _logger.LogError("Error: Unauthorized");
- return false;
- }
-
- if (httpResponseMessage.StatusCode != HttpStatusCode.OK)
- {
- _logger.LogError("Error");
- return false;
- }
-
- _logger.LogInformation($"Call pass");
- return true;
- }
- }
- }
|