Skip to content

Commit

Permalink
Merge pull request #2299 from SkillsFundingAgency/CON-4835-MI-pregapi
Browse files Browse the repository at this point in the history
CON-4835-EAS calls Provider Registrations API using MI credentials
  • Loading branch information
cofaulco authored Jun 15, 2022
2 parents bc1b719 + f2c7738 commit 530acda
Show file tree
Hide file tree
Showing 10 changed files with 241 additions and 54 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
using System;
using System.Configuration;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Moq;
using Moq.Protected;
using NUnit.Framework;
using SFA.DAS.EmployerAccounts.Configuration;
using SFA.DAS.EmployerAccounts.Interfaces;
using SFA.DAS.EmployerAccounts.Services;

namespace SFA.DAS.EmployerAccounts.UnitTests.Services.ProviderRegistration
{
class WhenIGetInvitation
{
private IProviderRegistrationApiClient _sut;
private ProviderRegistrationClientApiConfiguration _configuration;
private string _correlationId;
private string _testData;
private string _apiBaseUrl;
private string _identifierUri;
Mock<HttpMessageHandler> _mockHttpMessageHandler;
Mock<ILogger<ProviderRegistrationApiClient>> _logger;

[SetUp]
public void Arrange()
{
ConfigurationManager.AppSettings["EnvironmentName"] = "LOCAL";
_apiBaseUrl = $"http://{Guid.NewGuid().ToString()}/";
_identifierUri = Guid.NewGuid().ToString();
_correlationId = Guid.NewGuid().ToString();
_testData = "Employer details";

_logger = new Mock<ILogger<ProviderRegistrationApiClient>>();

_configuration = new ProviderRegistrationClientApiConfiguration
{
BaseUrl = _apiBaseUrl,
IdentifierUri = _identifierUri
};

_mockHttpMessageHandler = new Mock<HttpMessageHandler>();

_mockHttpMessageHandler
.Protected()
.Setup<Task<HttpResponseMessage>>("SendAsync",
ItExpr.IsAny<HttpRequestMessage>(),
ItExpr.IsAny<CancellationToken>())
.ReturnsAsync(new HttpResponseMessage
{
Content = new StringContent(_testData),
StatusCode = HttpStatusCode.OK
}
).Verifiable("");

var httpClient = new HttpClient(_mockHttpMessageHandler.Object);

_sut = new ProviderRegistrationApiClient(httpClient, _configuration, _logger.Object);
}

[Test]
public async Task Then_Verify_ProviderRegistrationApi_ToGetInvitationIsCalled()
{
//act
await _sut.GetInvitations(_correlationId);

//assert
_mockHttpMessageHandler
.Protected()
.Verify("SendAsync", Times.Once(),
ItExpr.Is<HttpRequestMessage>(r => r.Method == HttpMethod.Get
&& r.RequestUri.AbsoluteUri == $"{_configuration.BaseUrl}api/invitations/{_correlationId}"),
ItExpr.IsAny<CancellationToken>());
}

[Test]
public async Task WhenUnsubscribeProviderEmail_Then_Verify_ProviderRegistrationApiToUnsubscribeIsCalled()
{
//act
await _sut.Unsubscribe(_correlationId);

//assert
_mockHttpMessageHandler
.Protected()
.Verify("SendAsync", Times.Once(),
ItExpr.Is<HttpRequestMessage>(r => r.Method == HttpMethod.Get
&& r.RequestUri.AbsoluteUri == $"{_configuration.BaseUrl}api/unsubscribe/{_correlationId}"),
ItExpr.IsAny<CancellationToken>());
}

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ public static IContainer Initialize()
c.AddRegistry<CommitmentsV2ApiClientRegistry>();
c.AddRegistry<PollyPolicyRegistry>();
c.AddRegistry<ContentApiClientRegistry>();
c.AddRegistry<ProviderRegistrationApiClientRegistry>();
});
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,42 +1,25 @@
using System.Threading.Tasks;
using MediatR;
using SFA.DAS.EmployerAccounts.Configuration;
using SFA.DAS.EmployerAccounts.Interfaces;
using SFA.DAS.NLog.Logger;

namespace SFA.DAS.EmployerAccounts.Commands.UnsubscribeProviderEmail
{
public class UnsubscribeProviderEmailQueryHandler : AsyncRequestHandler<UnsubscribeProviderEmailQuery>
{
private readonly EmployerAccountsConfiguration _configuration;
private readonly IHttpService _httpService;
private readonly IProviderRegistrationApiClient _providerRegistrationApiClient;
private readonly ILog _logger;

public UnsubscribeProviderEmailQueryHandler(
IHttpServiceFactory httpServiceFactory,
EmployerAccountsConfiguration configuration)
public UnsubscribeProviderEmailQueryHandler(IProviderRegistrationApiClient providerRegistrationApiClient, ILog logger)
{
_configuration = configuration;
_httpService = httpServiceFactory.Create(
configuration.ProviderRegistrationsApi.IdentifierUri,
configuration.ProviderRegistrationsApi.ClientId,
configuration.ProviderRegistrationsApi.ClientSecret,
configuration.ProviderRegistrationsApi.Tenant
);
_providerRegistrationApiClient = providerRegistrationApiClient;
_logger = logger;
}

protected override async Task HandleCore(UnsubscribeProviderEmailQuery message)
{
var baseUrl = GetBaseUrl();
var url = $"{baseUrl}api/unsubscribe/{message.CorrelationId.ToString()}";
await _httpService.GetAsync(url, false);
}

private string GetBaseUrl()
{
var baseUrl = _configuration.ProviderRegistrationsApi.BaseUrl.EndsWith("/")
? _configuration.ProviderRegistrationsApi.BaseUrl
: _configuration.ProviderRegistrationsApi.BaseUrl + "/";

return baseUrl;
}
await _providerRegistrationApiClient.Unsubscribe(message.CorrelationId.ToString());
_logger.Info($"Sent ProviderEmail to Unsubscribe {message.CorrelationId}");
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public class EmployerAccountsConfiguration : ITopicMessagePublisherConfiguration
public string Hashstring { get; set; }
public HmrcConfiguration Hmrc { get; set; }
public PensionRegulatorConfiguration PensionRegulatorApi { get; set; }
public ProviderRegistrationsConfiguration ProviderRegistrationsApi { get; set; }
public ProviderRegistrationClientApiConfiguration ProviderRegistrationsApi { get; set; }
public IdentityServerConfiguration Identity { get; set; }
public string LegacyServiceBusConnectionString { get; set; }
public string MessageServiceBusConnectionString => LegacyServiceBusConnectionString;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
using SFA.DAS.EmployerAccounts.Interfaces;

namespace SFA.DAS.EmployerAccounts.Configuration
{
public class ProviderRegistrationClientApiConfiguration : IProviderRegistrationClientApiConfiguration
{
public string BaseUrl { get; set; }
public string IdentifierUri { get; set; }
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
using System.Net.Http;
using SFA.DAS.EmployerAccounts.Configuration;
using SFA.DAS.EmployerAccounts.Interfaces;
using SFA.DAS.EmployerAccounts.Services;
using SFA.DAS.Http;
using SFA.DAS.NLog.Logger.Web.MessageHandlers;
using StructureMap;

namespace SFA.DAS.EmployerAccounts.DependencyResolution
{
public class ProviderRegistrationApiClientRegistry : Registry
{
public ProviderRegistrationApiClientRegistry()
{
For<ProviderRegistrationClientApiConfiguration>().Use(c => c.GetInstance<EmployerAccountsConfiguration>().ProviderRegistrationsApi);
For<IProviderRegistrationClientApiConfiguration>().Use(c => c.GetInstance<ProviderRegistrationClientApiConfiguration>());
For<IProviderRegistrationApiClient>().Use<ProviderRegistrationApiClient>()
.Ctor<HttpClient>().Is(c => CreateClient(c));
}

private HttpClient CreateClient(IContext context)
{
HttpClient httpClient = new HttpClientBuilder()
.WithHandler(new RequestIdMessageRequestHandler())
.WithHandler(new SessionIdMessageRequestHandler())
.WithDefaultHeaders()
.Build();


return httpClient;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
using System.Threading.Tasks;

namespace SFA.DAS.EmployerAccounts.Interfaces
{
public interface IProviderRegistrationApiClient
{
Task Unsubscribe(string CorrelationId);

Task<string> GetInvitations(string CorrelationId);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@

namespace SFA.DAS.EmployerAccounts.Interfaces
{
public interface IProviderRegistrationClientApiConfiguration
{
string BaseUrl { get; }
string IdentifierUri { get; }
}
}
Original file line number Diff line number Diff line change
@@ -1,49 +1,32 @@
using System.Threading.Tasks;
using MediatR;
using SFA.DAS.EmployerAccounts.Configuration;
using SFA.DAS.EmployerAccounts.Interfaces;
using SFA.DAS.EmployerAccounts.Models;
using Newtonsoft.Json;
using SFA.DAS.EmployerAccounts.Interfaces;
using SFA.DAS.NLog.Logger;

namespace SFA.DAS.EmployerAccounts.Queries.GetProviderInvitation
{
public class GetProviderInvitationQueryHandler : IAsyncRequestHandler<GetProviderInvitationQuery, GetProviderInvitationResponse>
{
private readonly EmployerAccountsConfiguration _configuration;
private readonly IHttpService _httpService;
private readonly IProviderRegistrationApiClient _providerRegistrationApiClient;
private readonly ILog _logger;

public GetProviderInvitationQueryHandler(
IHttpServiceFactory httpServiceFactory,
EmployerAccountsConfiguration configuration)
public GetProviderInvitationQueryHandler(IProviderRegistrationApiClient providerRegistrationApiClient, ILog logger)
{
_configuration = configuration;
_httpService = httpServiceFactory.Create(
configuration.ProviderRegistrationsApi.IdentifierUri,
configuration.ProviderRegistrationsApi.ClientId,
configuration.ProviderRegistrationsApi.ClientSecret,
configuration.ProviderRegistrationsApi.Tenant
);
_providerRegistrationApiClient = providerRegistrationApiClient;
_logger = logger;
}

public async Task<GetProviderInvitationResponse> Handle(GetProviderInvitationQuery message)
{
var baseUrl = GetBaseUrl();
var url = $"{baseUrl}api/invitations/{message.CorrelationId.ToString()}";
var json = await _httpService.GetAsync(url, false);

_logger.Info($"Get Invitations for {message.CorrelationId}");
var json = await _providerRegistrationApiClient.GetInvitations(message.CorrelationId.ToString());
_logger.Info($"Request sent Get Invitations for {message.CorrelationId} {json}");
return new GetProviderInvitationResponse
{
Result = json == null ? null : JsonConvert.DeserializeObject<ProviderInvitation>(json)
};
}

private string GetBaseUrl()
{
var baseUrl = _configuration.ProviderRegistrationsApi.BaseUrl.EndsWith("/")
? _configuration.ProviderRegistrationsApi.BaseUrl
: _configuration.ProviderRegistrationsApi.BaseUrl + "/";

return baseUrl;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
using System.Configuration;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Microsoft.Azure.Services.AppAuthentication;
using Microsoft.Extensions.Logging;
using SFA.DAS.Authentication.Extensions.Legacy;
using SFA.DAS.EmployerAccounts.Interfaces;

namespace SFA.DAS.EmployerAccounts.Services
{
public class ProviderRegistrationApiClient : ApiClientBase, IProviderRegistrationApiClient
{
private readonly string _apiBaseUrl;
private readonly string _identifierUri;
private readonly HttpClient _client;
private readonly ILogger<ProviderRegistrationApiClient> _logger;

public ProviderRegistrationApiClient(HttpClient client, IProviderRegistrationClientApiConfiguration configuration, ILogger<ProviderRegistrationApiClient> logger) : base(client)
{
_apiBaseUrl = configuration.BaseUrl.EndsWith("/")
? configuration.BaseUrl
: configuration.BaseUrl + "/";

_identifierUri = configuration.IdentifierUri;
_client = client;
_logger = logger;
}

public async Task Unsubscribe(string CorrelationId)
{
await AddAuthenticationHeader();

var url = $"{_apiBaseUrl}api/unsubscribe/{CorrelationId}";
_logger.LogInformation($"Getting Unsubscribe {url}");
await _client.GetAsync(url);
}

public async Task<string> GetInvitations(string CorrelationId)
{
await AddAuthenticationHeader();

var url = $"{_apiBaseUrl}api/invitations/{CorrelationId}";
_logger.LogInformation($"Getting Invitations {url}");
var response = await _client.GetAsync(url);
response.EnsureSuccessStatusCode();

return await response.Content.ReadAsStringAsync().ConfigureAwait(false);
}

private async Task AddAuthenticationHeader()
{
if (ConfigurationManager.AppSettings["EnvironmentName"].ToUpper() != "LOCAL")
{
var azureServiceTokenProvider = new AzureServiceTokenProvider();
var accessToken = await azureServiceTokenProvider.GetAccessTokenAsync(_identifierUri);

_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
}
}
}
}

0 comments on commit 530acda

Please sign in to comment.