Bladeren bron

Merge branch 'feature/2189_screening_test_app_integration' of Neca/HRCenter into BE_dev

pull/131/head
safet.purkovic 3 jaren geleden
bovenliggende
commit
ec0b900f07

+ 10
- 0
Diligent.WebAPI.Business/Services/Interfaces/IScreeningTestClientService.cs Bestand weergeven

@@ -0,0 +1,10 @@
namespace Diligent.WebAPI.Business.Services.Interfaces
{
public interface IScreeningTestClientService
{
Task<AuthSuccessResponse> LoginToScreening(AuthenticateRequestDto model);
Task GetScreening();

}

}

+ 9
- 0
Diligent.WebAPI.Business/Services/Interfaces/IScreeningTestService.cs Bestand weergeven

@@ -0,0 +1,9 @@
namespace Diligent.WebAPI.Business.Services.Interfaces
{
public interface IScreeningTestService
{
Task<BaseResult<IEnumerable<TestMicroserviceRequest>>> GetScreening();
Task<bool> SendTest(TestMicroserviceInviteRequest test);
Task<AuthSuccessResponse> LoginToScreening();
}
}

+ 174
- 0
Diligent.WebAPI.Business/Services/ScreeningTestService.cs Bestand weergeven

@@ -0,0 +1,174 @@
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;
}
}
}

+ 10
- 0
Diligent.WebAPI.Business/Settings/ScreeningTestSettings.cs Bestand weergeven

@@ -0,0 +1,10 @@
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; }
}
}

+ 8
- 0
Diligent.WebAPI.Contracts/Models/AuthMicroserviceRequest.cs Bestand weergeven

@@ -0,0 +1,8 @@
namespace Diligent.WebAPI.Contracts.Models
{
public class AuthMicroserviceRequest
{
public string Email { get; set; }
public string Password { get; set; }
}
}

+ 8
- 0
Diligent.WebAPI.Contracts/Models/AuthSuccessResponse.cs Bestand weergeven

@@ -0,0 +1,8 @@
namespace Diligent.WebAPI.Contracts.Models
{
public class AuthSuccessResponse
{
public string Token { get; set; }
public DateTime? Expires { get; set; }
}
}

+ 11
- 0
Diligent.WebAPI.Contracts/Models/TestMicroserviceInviteRequest.cs Bestand weergeven

@@ -0,0 +1,11 @@
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; }
}
}

+ 8
- 0
Diligent.WebAPI.Contracts/Models/TestMicroserviceRequest.cs Bestand weergeven

@@ -0,0 +1,8 @@
namespace Diligent.WebAPI.Contracts.Models
{
public class TestMicroserviceRequest
{
public int Id { get; set; }
public string Name { get; set; }
}
}

+ 35
- 0
Diligent.WebAPI.Host/Controllers/V1/ScreeningTestController.cs Bestand weergeven

@@ -0,0 +1,35 @@
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();
}
}
}

+ 1
- 0
Diligent.WebAPI.Host/Extensions/AuthConfigurationExtension.cs Bestand weergeven

@@ -5,6 +5,7 @@
public static void ConfigureAuth(this WebApplicationBuilder builder)
{
builder.Services.Configure<AuthorizationSettings>(builder.Configuration.GetSection("Authorization"));
builder.Services.Configure<ScreeningTestSettings>(builder.Configuration.GetSection("ScreeningTest"));
builder.Services.AddScoped<IUserService, UserService>();
}
}}

+ 1
- 0
Diligent.WebAPI.Host/Extensions/BusinessConfigurationExtension.cs Bestand weergeven

@@ -36,6 +36,7 @@
services.AddScoped<IScheduleService, ScheduleService>();
services.AddScoped<IImportService, ImportService>();
services.AddScoped<ISaveImportedDataService, SaveImportedDataService>();
services.AddScoped<IScreeningTestService, ScreeningTestService>();
}

/// <summary>

+ 26
- 0
Diligent.WebAPI.Host/Extensions/CacheModelExtension.cs Bestand weergeven

@@ -0,0 +1,26 @@
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 "";
}
}
}

+ 1
- 0
Diligent.WebAPI.Host/Extensions/HostConfigurationExtension.cs Bestand weergeven

@@ -15,6 +15,7 @@
builder.ConfigureSwagger();

IServiceCollection services = builder.Services;
services.AddMemoryCache();
services.AddHttpContextAccessor();
services.AddControllers();
services.AddEndpointsApiExplorer();

+ 0
- 2
Diligent.WebAPI.Host/Program.cs Bestand weergeven

@@ -12,8 +12,6 @@ try

builder.Host.UseSerilog((context, services, configuration) => configuration.ReadFrom.Configuration(context.Configuration).ReadFrom.Services(services).Enrich.FromLogContext());



builder.ConfigureHost();
builder.ConfigureData();
builder.ConfigureBusiness();

+ 8
- 2
Diligent.WebAPI.Host/appsettings.Development.json Bestand weergeven

@@ -42,6 +42,12 @@
"SmtpFromName": "HRCenter Team"
},
"FrontEnd": {
"BaseUrl": "http://localhost:3000"
"BaseUrl": "http://localhost:3000",
},
"ScreeningTest": {
"Url": "https://localhost:44349/api/v1/",
"Email": "hrcenter@dilig.net",
"Password": "MYRandomPass135!",
"link": "https://localhost:44336/Intern/ToS?id={0}"
}
}
}

Laden…
Annuleren
Opslaan