Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
1dbadd4
added prefill from Dan to PrefillSI.cs
pernillehofgaard Dec 9, 2025
0d7bfa5
updated interface with correct parameters
pernillehofgaard Dec 9, 2025
76eef15
added danClient
pernillehofgaard Dec 9, 2025
0a232ce
fixed tests
pernillehofgaard Dec 16, 2025
4688744
DanClient returns dictionary
pernillehofgaard Dec 16, 2025
e3b555f
removed hardcoding of subject
pernillehofgaard Dec 16, 2025
2f02bc4
use SwapKeyValuesForPrefill so documentation is accurate
pernillehofgaard Dec 16, 2025
dde9af6
added xml comments to classes, methods and properties
pernillehofgaard Dec 17, 2025
9e53974
added query-jmespath to api call and helper methods
pernillehofgaard Jan 6, 2026
fcc1d42
Only use the json key as jmespath
pernillehofgaard Jan 7, 2026
8a5d15f
cleaned up in code
pernillehofgaard Jan 8, 2026
bc7a914
Fixed tests
pernillehofgaard Jan 8, 2026
aab9fe7
added comments and cleaned up in code
pernillehofgaard Jan 12, 2026
3d94d7a
fixed null references and warnings
pernillehofgaard Jan 12, 2026
ae93171
cleaned up and removed unnecessary code
pernillehofgaard Jan 13, 2026
77d68fe
removed unused code
pernillehofgaard Jan 13, 2026
96719e7
Removed unused packages
pernillehofgaard Jan 14, 2026
e33ca33
move headers to constructor
pernillehofgaard Jan 14, 2026
b7900dc
Added DanClientMock and fixed tests
pernillehofgaard Jan 14, 2026
f59f86d
Return empty dictionary if fields are not specified
pernillehofgaard Jan 14, 2026
775f4c7
added null check for subject and dataset name
pernillehofgaard Jan 14, 2026
94ade4f
moved dan DI to correct method
pernillehofgaard Jan 14, 2026
90e3014
removed mocked client
pernillehofgaard Jan 14, 2026
b92b403
removed unneccessary code and added null check
pernillehofgaard Jan 14, 2026
838af72
Added test for prefill of Dan data
pernillehofgaard Jan 15, 2026
fd65707
various fixes recommended på codeQL and coderabbit
pernillehofgaard Jan 15, 2026
2d7bd80
fixed test
pernillehofgaard Jan 19, 2026
39d11d5
Made fields in test model nullable
pernillehofgaard Jan 19, 2026
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
1 change: 0 additions & 1 deletion src/Altinn.App.Core/Altinn.App.Core.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
<!-- The following packages uses frozen version because of compatibility considerations for apps -->
<!-- See: https://github.com/Altinn/app-lib-dotnet/issues/647 -->
<PackageReference Include="Altinn.ApiClients.Maskinporten"/>

<PackageReference Include="JWTCookieAuthentication"/>
<!-- The follwoing are depencencies for JWTCookieAuthentication, but we need newer versions-->
<PackageReference Include="Microsoft.IdentityModel.Protocols.OpenIdConnect" />
Expand Down
17 changes: 17 additions & 0 deletions src/Altinn.App.Core/Configuration/DanSettings.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
namespace Altinn.App.Core.Configuration;

/// <summary>
/// Settings for DanClient
/// </summary>
public class DanSettings
{
/// <summary>
/// Base url for Dan API
/// </summary>
public required string BaseUrl { get; set; }

/// <summary>
/// Api subscription keys
/// </summary>
public required string SubscriptionKey { get; set; }
}
8 changes: 8 additions & 0 deletions src/Altinn.App.Core/Extensions/ServiceCollectionExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
using Altinn.App.Core.Infrastructure.Clients.AccessManagement;
using Altinn.App.Core.Infrastructure.Clients.Authentication;
using Altinn.App.Core.Infrastructure.Clients.Authorization;
using Altinn.App.Core.Infrastructure.Clients.Dan;
using Altinn.App.Core.Infrastructure.Clients.Events;
using Altinn.App.Core.Infrastructure.Clients.KeyVault;
using Altinn.App.Core.Infrastructure.Clients.Pdf;
Expand All @@ -36,6 +37,7 @@
using Altinn.App.Core.Internal.App;
using Altinn.App.Core.Internal.AppModel;
using Altinn.App.Core.Internal.Auth;
using Altinn.App.Core.Internal.Dan;
using Altinn.App.Core.Internal.Data;
using Altinn.App.Core.Internal.Events;
using Altinn.App.Core.Internal.Expressions;
Expand Down Expand Up @@ -195,6 +197,12 @@ IWebHostEnvironment env
services.Configure<AccessTokenSettings>(configuration.GetSection("AccessTokenSettings"));
services.Configure<FrontEndSettings>(configuration.GetSection(nameof(FrontEndSettings)));
services.Configure<PdfGeneratorSettings>(configuration.GetSection(nameof(PdfGeneratorSettings)));
var danSettings = configuration.GetSection("DanClientSettings");
if (danSettings.Exists())
{
services.AddHttpClient<IDanClient, DanClient>();
services.Configure<DanSettings>(danSettings);
}

services.AddRuntimeEnvironment();
if (env.IsDevelopment())
Expand Down
63 changes: 63 additions & 0 deletions src/Altinn.App.Core/Implementation/PrefillSI.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using Altinn.App.Core.Features;
using Altinn.App.Core.Features.Auth;
using Altinn.App.Core.Internal.App;
using Altinn.App.Core.Internal.Dan;
using Altinn.App.Core.Internal.Prefill;
using Altinn.App.Core.Internal.Registers;
using Altinn.Platform.Profile.Models;
Expand All @@ -20,10 +21,12 @@ public class PrefillSI : IPrefill
private readonly IAppResources _appResourcesService;
private readonly IRegisterClient _registerClient;
private readonly IAuthenticationContext _authenticationContext;
private readonly IDanClient? _danClient;
private readonly Telemetry? _telemetry;
private static readonly string _erKey = "ER";
private static readonly string _dsfKey = "DSF";
private static readonly string _userProfileKey = "UserProfile";
private static readonly string _danKey = "DAN";
private static readonly string _allowOverwriteKey = "allowOverwrite";
private bool _allowOverwrite = false;

Expand All @@ -34,19 +37,22 @@ public class PrefillSI : IPrefill
/// <param name="appResourcesService">The app's resource service</param>
/// <param name="authenticationContext">The authentication context</param>
/// <param name="serviceProvider">The service provider</param>
/// <param name="danClient">The Dan client</param>
/// <param name="telemetry">Telemetry for traces and metrics.</param>
public PrefillSI(
ILogger<PrefillSI> logger,
IAppResources appResourcesService,
IAuthenticationContext authenticationContext,
IServiceProvider serviceProvider,
IDanClient? danClient = null,
Telemetry? telemetry = null
)
{
_logger = logger;
_appResourcesService = appResourcesService;
_registerClient = serviceProvider.GetRequiredService<IRegisterClient>();
_authenticationContext = authenticationContext;
_danClient = danClient;
_telemetry = telemetry;
}

Expand Down Expand Up @@ -206,6 +212,63 @@ when await systemUser.LoadDetails() is { } details && details.Party.PartyId == p
}
}
}

// Prefill from Dan
JToken? danConfiguration = prefillConfiguration.SelectToken(_danKey);
if (danConfiguration != null && _danClient != null)
{
var datasetList = danConfiguration.SelectToken("datasets");
if (datasetList != null)
{
foreach (var dataset in datasetList)
{
var datasetName = dataset.SelectToken("name")?.ToString();
var subject = !string.IsNullOrWhiteSpace(party.SSN) ? party.SSN : party.OrgNumber;

if (string.IsNullOrEmpty(subject))
{
_logger.LogError(
"Could not prefill from {DanKey}, no valid subject (SSN or OrgNumber) found for party",
_danKey
);
continue;
}

var fields = dataset.SelectToken("mappings");
if (fields != null)
{
var danPrefill = fields
.SelectMany(obj => obj.Children<JProperty>())
.ToDictionary(prop => prop.Name, prop => prop.Value.ToString());

if (datasetName != null)
{
var danDataset = await _danClient.GetDataset(datasetName, subject, fields.ToString());
if (danDataset.Count > 0)
{
JObject danJsonObject = JObject.FromObject(danDataset);
_logger.LogInformation($"Started prefill from {_danKey}");
LoopThroughDictionaryAndAssignValuesToDataModel(
SwapKeyValuesForPrefill(danPrefill),
danJsonObject,
dataModel
);
}
else
{
string errorMessage = $"Could not prefill from {_danKey}, data is not defined.";
_logger.LogError(errorMessage);
}
}
else
{
string errorMessage = $"Could not prefill from {_danKey}, dataset name is not defined.";
_logger.LogError(errorMessage);
}
}
}
}
}
}

/// <summary>
Expand Down
117 changes: 117 additions & 0 deletions src/Altinn.App.Core/Infrastructure/Clients/Dan/DanClient.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
using System.Text;
using System.Text.Json;
using Altinn.App.Core.Configuration;
using Altinn.App.Core.Internal.Dan;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using JsonException = Newtonsoft.Json.JsonException;
using JsonSerializer = System.Text.Json.JsonSerializer;

namespace Altinn.App.Core.Infrastructure.Clients.Dan;

/// <summary>
/// Client for interacting with the Dan API.
/// </summary>
public class DanClient : IDanClient
{
private readonly HttpClient _httpClient;
private readonly IOptions<DanSettings> _settings;

/// <summary>
/// Constructor
/// </summary>
/// <param name="factory"></param>
/// <param name="settings"></param>
public DanClient(IHttpClientFactory factory, IOptions<DanSettings> settings)
{
_httpClient = factory.CreateClient("DanClient");
_settings = settings;

_httpClient.DefaultRequestHeaders.Clear();
_httpClient.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", _settings.Value.SubscriptionKey);
_httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
_httpClient.BaseAddress = new Uri(settings.Value.BaseUrl);
}

/// <summary>
/// Returns dataset from Dan API.
/// </summary>
/// <param name="dataset">Dataset from Dan</param>
/// <param name="subject">Usually ssn or orgNumber</param>
/// <param name="fields">The fields we fetch from the api</param>
/// <returns></returns>
public async Task<Dictionary<string, string>> GetDataset(string dataset, string subject, string fields)
{
var body = new { Subject = subject };
var myContent = JsonConvert.SerializeObject(body);

var fieldsToFill = GetQuery(fields);
if (fieldsToFill.Count == 0)
return new Dictionary<string, string>();

var baseQuery = $"{fieldsToFill.First()} : {fieldsToFill.First()}";
foreach (var jsonKey in fieldsToFill.Skip(1))
{
//if there is more than one field to fetch, add it to the query
baseQuery += $",{jsonKey} : {jsonKey}";

Check notice

Code scanning / CodeQL

String concatenation in loop Note

String concatenation in loop: use 'StringBuilder'.
}

//ensures that the query returns a list if endpoint returns a list and an object when endpoint returns a single object
var query = "[].{" + baseQuery + "}||{" + baseQuery + "}";
using (var content = new StringContent(myContent, Encoding.UTF8, "application/json"))
{
var result = await _httpClient.PostAsync(
$"directharvest/{dataset}?envelope=false&reuseToken=true&query={query}",
content
);

if (result.IsSuccessStatusCode)
{
Dictionary<string, string>? dictionary;

var resultJson = await result.Content.ReadAsStringAsync();

dictionary = IsJsonArray(resultJson)
? await ConvertListToDictionary(resultJson)
: JsonConvert.DeserializeObject<Dictionary<string, string>>(resultJson);

return dictionary ?? new Dictionary<string, string>();
}
}
return new Dictionary<string, string>();
}

private static Task<Dictionary<string, string>> ConvertListToDictionary(string jsonString)
{
var list = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(jsonString);
if (list != null)
return Task.FromResult(
list.SelectMany(d => d)
.GroupBy(kvp => kvp.Key)
.ToDictionary(g => g.Key, g => string.Join(",", g.Select(x => x.Value)))
);

return Task.FromResult(new Dictionary<string, string>());
}

private static bool IsJsonArray(string jsonString)
{
try
{
using var doc = JsonDocument.Parse(jsonString);
return doc.RootElement.ValueKind == JsonValueKind.Array;
}
catch (JsonException)
{
return false;
}
}

private static List<string> GetQuery(string json)
{
var list = JsonSerializer.Deserialize<List<Dictionary<string, string>>>(json);
if (list != null)
return list.Where(l => l.Count != 0).Select(l => l.Keys.First()).ToList();
return new List<string>();
}
}
16 changes: 16 additions & 0 deletions src/Altinn.App.Core/Internal/Dan/IDanClient.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
namespace Altinn.App.Core.Internal.Dan;

/// <summary>
/// DanClient interface
/// </summary>
public interface IDanClient
{
/// <summary>
/// Method for getting a selected dataset from Dan Api
/// </summary>
/// <param name="dataset">Name of the dataset</param>
/// <param name="subject">Usually ssn or OrgNumber</param>
/// <param name="fields">fields to fetch from endpoint</param>
/// <returns></returns>
public Task<Dictionary<string, string>> GetDataset(string dataset, string subject, string fields);
}
7 changes: 7 additions & 0 deletions test/Altinn.App.Api.Tests/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,11 @@
using Altinn.App.Core.Configuration;
using Altinn.App.Core.Features;
using Altinn.App.Core.Features.Cache;
using Altinn.App.Core.Infrastructure.Clients.Dan;
using Altinn.App.Core.Internal.App;
using Altinn.App.Core.Internal.AppModel;
using Altinn.App.Core.Internal.Auth;
using Altinn.App.Core.Internal.Dan;
using Altinn.App.Core.Internal.Data;
using Altinn.App.Core.Internal.Events;
using Altinn.App.Core.Internal.Instances;
Expand Down Expand Up @@ -67,6 +69,11 @@
builder.Services.Configure<GeneralSettings>(settings => settings.DisableLocaltestValidation = true);
builder.Services.Configure<GeneralSettings>(settings => settings.DisableAppConfigurationCache = true);
builder.Services.Configure<GeneralSettings>(settings => settings.IsTest = true);
builder.Services.Configure<DanSettings>(settings =>
{
settings.BaseUrl = "http://localhost:7071/v1/";
settings.SubscriptionKey = "test-subscription-key";
});
builder.Configuration.GetSection("GeneralSettings:IsTest").Value = "true";

// AppConfigurationCache.Disable = true;
Expand Down
Loading
Loading