Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add name lookups #532

Merged
merged 1 commit into from
Mar 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,28 +1,93 @@
using System.Globalization;
using Bogus;
using System.Net;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using Digdir.Domain.Dialogporten.Application.Externals;
using Digdir.Domain.Dialogporten.Infrastructure.Common.Extensions;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Logging;

namespace Digdir.Domain.Dialogporten.Infrastructure.Altinn.OrganizationRegistry;

internal class NameRegistryClient : INameRegistry
{
private static readonly DistributedCacheEntryOptions _oneDayCacheDuration = new() { AbsoluteExpiration = DateTimeOffset.UtcNow.AddDays(1) };
private static readonly DistributedCacheEntryOptions _zeroCacheDuration = new() { AbsoluteExpiration = DateTimeOffset.MinValue };

private readonly IDistributedCache _cache;
private readonly HttpClient _client;
private readonly ILogger<NameRegistryClient> _logger;

private static readonly JsonSerializerOptions _serializerOptions = new()

{
PropertyNameCaseInsensitive = true,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault
};

public NameRegistryClient(HttpClient client, IDistributedCache cache)
public NameRegistryClient(HttpClient client, IDistributedCache cache, ILogger<NameRegistryClient> logger)
{
_client = client ?? throw new ArgumentNullException(nameof(client));
_cache = cache ?? throw new ArgumentNullException(nameof(cache));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}

public async Task<string?> GetName(string personalIdentificationNumber, CancellationToken cancellationToken)
{
// TODO: Implement fetching from Altinn
// https://github.com/digdir/dialogporten/issues/321
Randomizer.Seed = new Random((int)long.Parse(personalIdentificationNumber, new NumberFormatInfo()));
var name = new Faker().Name.FullName();
return await _cache.GetOrAddAsync(
$"Name_{personalIdentificationNumber}",
(ct) => GetNameFromRegister(personalIdentificationNumber, ct),
CacheOptionsFactory,
cancellationToken: cancellationToken);
}

private static DistributedCacheEntryOptions CacheOptionsFactory(string? name) =>
name is not null ? _oneDayCacheDuration : _zeroCacheDuration;

private async Task<string?> GetNameFromRegister(string personalIdentificationNumber, CancellationToken cancellationToken)
{
const string apiUrl = "register/api/v1/parties/nameslookup";

var nameLookup = new NameLookup
{
Parties = [
new() { Ssn = personalIdentificationNumber }
]
};

var requestJson = JsonSerializer.Serialize(nameLookup, _serializerOptions);
var httpContent = new StringContent(requestJson, Encoding.UTF8, "application/json");

var response = await _client.PostAsync(apiUrl, httpContent, cancellationToken);

if (response.StatusCode != HttpStatusCode.OK)
{
var errorResponse = await response.Content.ReadAsStringAsync(cancellationToken);
_logger.LogWarning(
nameof(NameRegistryClient) + ".SendRequest failed with non-successful status code: {StatusCode} {Response}",
response.StatusCode, errorResponse);

return null;
}

var responseData = await response.Content.ReadAsStringAsync(cancellationToken);
var nameLookupResult = JsonSerializer.Deserialize<NameLookupResult>(responseData, _serializerOptions);
return nameLookupResult?.PartyNames.FirstOrDefault()?.Name;
}

private sealed class NameLookup
{
public List<NameLookupSsn> Parties { get; set; } = null!;
}

return await Task.FromResult(name);
private sealed class NameLookupResult
{
public List<NameLookupSsn> PartyNames { get; set; } = null!;
}

private sealed class NameLookupSsn
{
public string Ssn { get; set; } = null!;
public string? Name { get; set; }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -95,9 +95,15 @@ public static IServiceCollection AddInfrastructure(this IServiceCollection servi
client.BaseAddress = services.GetRequiredService<IOptions<InfrastructureSettings>>().Value.AltinnCdn.BaseUri)
.AddPolicyHandlerFromRegistry(PollyPolicy.DefaultHttpRetryPolicy);

services.AddHttpClient<INameRegistry, NameRegistryClient>((services, client) =>
// TODO: Correct base URL, https://github.com/digdir/dialogporten/issues/321
client.BaseAddress = services.GetRequiredService<IOptions<InfrastructureSettings>>().Value.Altinn.BaseUri)
services.AddMaskinportenHttpClient<INameRegistry, NameRegistryClient, SettingsJwkClientDefinition>(
infrastructureConfigurationSection,
x => x.ClientSettings.ExhangeToAltinnToken = true)
.ConfigureHttpClient((services, client) =>
{
var altinnSettings = services.GetRequiredService<IOptions<InfrastructureSettings>>().Value.Altinn;
client.BaseAddress = altinnSettings.BaseUri;
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", altinnSettings.SubscriptionKey);
})
.AddPolicyHandlerFromRegistry(PollyPolicy.DefaultHttpRetryPolicy);

services.AddHttpClient<IAltinnAuthorization, AltinnAuthorizationClient>((services, client) =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
// 2. Client Id/integration as configured in Maskinporten
"ClientId": "TODO: Add to local secrets",
// 3. Scope(s) requested, space seperated. Must be provisioned on supplied client id.
"Scope": "altinn:events.publish altinn:events.publish.admin",
"Scope": "altinn:events.publish altinn:events.publish.admin altinn:register/partylookup.admin",
// --------------------------
// Any additional settings are specific for the selected client definition type.
// See below for examples using other types.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
"ClientId": "TODO: Add to local secrets",

// 3. Scope(s) requested, space seperated. Must be provisioned on supplied client id.
"Scope": "altinn:events.publish altinn:events.publish.admin",
"Scope": "altinn:events.publish altinn:events.publish.admin altinn:register/partylookup.admin",

// --------------------------
// Any additional settings are specific for the selected client definition type.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
"ClientId": "TODO: Add to local secrets",

// 3. Scope(s) requested, space seperated. Must be provisioned on supplied client id.
"Scope": "altinn:events.publish altinn:events.publish.admin",
"Scope": "altinn:events.publish altinn:events.publish.admin altinn:register/partylookup.admin",

// --------------------------
// Any additional settings are specific for the selected client definition type.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
"ClientId": "TODO: Add to local secrets",

// 3. Scope(s) requested, space seperated. Must be provisioned on supplied client id.
"Scope": "altinn:events.publish altinn:events.publish.admin",
"Scope": "altinn:events.publish altinn:events.publish.admin altinn:register/partylookup.admin",

// --------------------------
// Any additional settings are specific for the selected client definition type.
Expand Down