| namespace Diligent.WebAPI.Business.Services.Interfaces | |||||
| { | |||||
| public interface IScreeningTestClientService | |||||
| { | |||||
| Task<AuthSuccessResponse> LoginToScreening(AuthenticateRequestDto model); | |||||
| Task GetScreening(); | |||||
| } | |||||
| } |
| namespace Diligent.WebAPI.Business.Services.Interfaces | |||||
| { | |||||
| public interface IScreeningTestService | |||||
| { | |||||
| Task<BaseResult<IEnumerable<TestMicroserviceRequest>>> GetScreening(); | |||||
| Task<bool> SendTest(TestMicroserviceInviteRequest test); | |||||
| Task<AuthSuccessResponse> LoginToScreening(); | |||||
| } | |||||
| } |
| 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)) | |||||
| { | |||||
| 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"); | |||||
| 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; | |||||
| } | |||||
| } | |||||
| } |
| namespace Diligent.WebAPI.Business.Settings | |||||
| { | |||||
| public class ScreeningTestSettings | |||||
| { | |||||
| public string Url { get; set; } | |||||
| public string Email { get; set; } | |||||
| public string Password { get; set; } | |||||
| public string Link { get; set; } | |||||
| } | |||||
| } |
| namespace Diligent.WebAPI.Contracts.Models | |||||
| { | |||||
| public class AuthMicroserviceRequest | |||||
| { | |||||
| public string Email { get; set; } | |||||
| public string Password { get; set; } | |||||
| } | |||||
| } |
| namespace Diligent.WebAPI.Contracts.Models | |||||
| { | |||||
| public class AuthSuccessResponse | |||||
| { | |||||
| public string Token { get; set; } | |||||
| public DateTime? Expires { get; set; } | |||||
| } | |||||
| } |
| namespace Diligent.WebAPI.Contracts.Models | |||||
| { | |||||
| public class TestMicroserviceInviteRequest | |||||
| { | |||||
| public string AdminEmail { get; set; } | |||||
| public string Email { get; set; } | |||||
| public int Duration { get; set; } | |||||
| public int TestId { get; set; } | |||||
| public string Url { get; set; } | |||||
| } | |||||
| } |
| namespace Diligent.WebAPI.Contracts.Models | |||||
| { | |||||
| public class TestMicroserviceRequest | |||||
| { | |||||
| public int Id { get; set; } | |||||
| public string Name { get; set; } | |||||
| } | |||||
| } |
| using Diligent.WebAPI.Business.Services; | |||||
| using Diligent.WebAPI.Business.Services.Interfaces; | |||||
| using Microsoft.AspNetCore.Mvc; | |||||
| using Microsoft.Extensions.Caching.Memory; | |||||
| namespace Diligent.WebAPI.Host.Controllers.V1 | |||||
| { | |||||
| [ApiController] | |||||
| [ApiVersion("1.0")] | |||||
| [Route("v{version:apiVersion}/screeningtest")] | |||||
| public class ScreeningTestController : Controller | |||||
| { | |||||
| private readonly IScreeningTestService _httpClientService; | |||||
| public ScreeningTestController(IScreeningTestService httpClientService) | |||||
| { | |||||
| _httpClientService = httpClientService; | |||||
| } | |||||
| [HttpGet] | |||||
| public async Task<ActionResult> Get() | |||||
| { | |||||
| var result = await _httpClientService.GetScreening(); | |||||
| if (!result.IsSuccess) | |||||
| return BadRequest(); | |||||
| return Ok(result.DataObject); | |||||
| } | |||||
| [HttpPost] | |||||
| public async Task<ActionResult> Post([FromBody]TestMicroserviceInviteRequest model) | |||||
| { | |||||
| var result = await _httpClientService.SendTest(model); | |||||
| if (!result) | |||||
| return BadRequest(); | |||||
| return Ok(); | |||||
| } | |||||
| } | |||||
| } |
| public static void ConfigureAuth(this WebApplicationBuilder builder) | public static void ConfigureAuth(this WebApplicationBuilder builder) | ||||
| { | { | ||||
| builder.Services.Configure<AuthorizationSettings>(builder.Configuration.GetSection("Authorization")); | builder.Services.Configure<AuthorizationSettings>(builder.Configuration.GetSection("Authorization")); | ||||
| builder.Services.Configure<ScreeningTestSettings>(builder.Configuration.GetSection("ScreeningTest")); | |||||
| builder.Services.AddScoped<IUserService, UserService>(); | builder.Services.AddScoped<IUserService, UserService>(); | ||||
| } | } | ||||
| }} | }} |
| services.AddScoped<IScheduleService, ScheduleService>(); | services.AddScoped<IScheduleService, ScheduleService>(); | ||||
| services.AddScoped<IImportService, ImportService>(); | services.AddScoped<IImportService, ImportService>(); | ||||
| services.AddScoped<ISaveImportedDataService, SaveImportedDataService>(); | services.AddScoped<ISaveImportedDataService, SaveImportedDataService>(); | ||||
| services.AddScoped<IScreeningTestService, ScreeningTestService>(); | |||||
| } | } | ||||
| /// <summary> | /// <summary> |
| using Microsoft.Extensions.Caching.Memory; | |||||
| namespace Diligent.WebAPI.Host.Extensions | |||||
| { | |||||
| public class CacheModelExtension | |||||
| { | |||||
| private static readonly IMemoryCache _memoryCache = new MemoryCache(new MemoryCacheOptions()); | |||||
| public static void AddCache(string cacheKey, string value, DateTime expiritaion) | |||||
| { | |||||
| var cacheExipiryOptions = new MemoryCacheEntryOptions | |||||
| { | |||||
| AbsoluteExpiration = expiritaion, | |||||
| Priority = CacheItemPriority.High, | |||||
| SlidingExpiration = TimeSpan.FromSeconds(20) | |||||
| }; | |||||
| _memoryCache.Set(cacheKey, value, cacheExipiryOptions); | |||||
| } | |||||
| public static string GetCache(string cacheKey) | |||||
| { | |||||
| if (_memoryCache.TryGetValue<string>(cacheKey, out var result)) | |||||
| return result; ; | |||||
| return ""; | |||||
| } | |||||
| } | |||||
| } |
| builder.ConfigureSwagger(); | builder.ConfigureSwagger(); | ||||
| IServiceCollection services = builder.Services; | IServiceCollection services = builder.Services; | ||||
| services.AddMemoryCache(); | |||||
| services.AddHttpContextAccessor(); | services.AddHttpContextAccessor(); | ||||
| services.AddControllers(); | services.AddControllers(); | ||||
| services.AddEndpointsApiExplorer(); | services.AddEndpointsApiExplorer(); |
| builder.Host.UseSerilog((context, services, configuration) => configuration.ReadFrom.Configuration(context.Configuration).ReadFrom.Services(services).Enrich.FromLogContext()); | builder.Host.UseSerilog((context, services, configuration) => configuration.ReadFrom.Configuration(context.Configuration).ReadFrom.Services(services).Enrich.FromLogContext()); | ||||
| builder.ConfigureHost(); | builder.ConfigureHost(); | ||||
| builder.ConfigureData(); | builder.ConfigureData(); | ||||
| builder.ConfigureBusiness(); | builder.ConfigureBusiness(); |
| "SmtpFromName": "HRCenter Team" | "SmtpFromName": "HRCenter Team" | ||||
| }, | }, | ||||
| "FrontEnd": { | "FrontEnd": { | ||||
| "BaseUrl": "http://localhost:3000" | |||||
| "BaseUrl": "http://localhost:3000", | |||||
| }, | |||||
| "ScreeningTest": { | |||||
| "Url": "https://localhost:44349/api/v1/", | |||||
| "Email": "bronjaerminn@gmail.com", | |||||
| "Password": "Ermin 12345!", | |||||
| "link": "https://localhost:44336/Intern/ToS?id={0}" | |||||
| } | |||||
| } | } | ||||
| } |