Skip to content

Commit

Permalink
move logic to bff and remove unused files (#955)
Browse files Browse the repository at this point in the history
* move logic to bff and remove unused files

* rename file

* feat: Add successful and failed API delegations to ConfirmationPage

The code changes in this commit add the functionality to display successful and failed API delegations on the ConfirmationPage. This is achieved by filtering the data received from the API and storing the successful and failed delegations separately. The color of the page is also updated based on the presence of failed or successful delegations.

* Update property names in ApiDelegationOutput and ApiDelegationResult

* Refactor APIDelegationController endpoint to support multiple third party organizations

* Refactor APIDelegationController endpoint to support multiple third party organizations

* Add batch delegation api test

* remove unused setting

* Refactor API delegation endpoint to remove unnecessary message property

* Refactor API delegation endpoint to remove unnecessary message property

* Refactor test

* chore: Remove logging of exception in APIDelegationController

* Refactor useTranslation hook in ConfirmationPage component

* chore: Remove exception logging in APIDelegationController

* chore: Refactor APIDelegationController to remove unnecessary exception logging and merge conflicts

* chore: Handle exception in CreateMaskinportenDelegationBatch endpoint
  • Loading branch information
sonwit authored Jul 3, 2024
1 parent ec869b1 commit 262626f
Show file tree
Hide file tree
Showing 27 changed files with 519 additions and 412 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
using System.ComponentModel.DataAnnotations;

namespace Altinn.AccessManagement.UI.Core.Models
{
/// <summary>
/// Model for performing a delegation of one or more rights to one or more recipients.
/// </summary>
public class ApiDelegationInput
{
/// <summary>
/// Gets or sets the list of organization numbers. This field is required.
/// </summary>
public List<string> OrgNumbers { get; set; }

/// <summary>
/// Gets or sets the list of API identifiers. This field is required.
/// </summary>
public List<string> ApiIdentifiers { get; set; }
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
using Altinn.AccessManagement.UI.Core.Models.SingleRight;

namespace Altinn.AccessManagement.UI.Core.Models
{
/// <summary>
/// Response model for the result of a api-delegation to a recipient.
/// </summary>
public class ApiDelegationOutput
{
/// <summary>
/// Gets or sets the organization identifier.
/// </summary>
public string OrgNumber { get; set; }

/// <summary>
/// Gets or sets the API identifier.
/// </summary>
public string ApiId { get; set; }

/// <summary>
/// Gets or sets a value indicating whether the operation was successful.
/// </summary>
public bool Success { get; set; }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ namespace Altinn.AccessManagement.UI.Core.Models
/// <summary>
/// Response model for the result of a delegation of one or more rights to a recipient.
/// </summary>
public class DelegationOutput
public class DelegationOutput
{
/// <summary>
/// Attribute id and value for the party delegating the rights
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Altinn.AccessManagement.UI.Core.ClientInterfaces;
using System.Text.Json;
using Altinn.AccessManagement.UI.Core.ClientInterfaces;
using Altinn.AccessManagement.UI.Core.Models;
using Altinn.AccessManagement.UI.Core.Models.Delegation;
using Altinn.AccessManagement.UI.Core.Models.Delegation.Frontend;
Expand All @@ -16,6 +17,11 @@ public class APIDelegationService : IAPIDelegationService
private readonly IAccessManagementClient _maskinportenSchemaClient;
private readonly IResourceService _resourceService;

private readonly JsonSerializerOptions _serializerOptions = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
};

/// <summary>
/// Initializes a new instance of the <see cref="APIDelegationService" /> class.
/// </summary>
Expand Down Expand Up @@ -61,6 +67,54 @@ public async Task<HttpResponseMessage> CreateMaskinportenScopeDelegation(string
return await _maskinportenSchemaClient.CreateMaskinportenScopeDelegation(party, delegation);
}

/// <inheritdoc />
public async Task<List<ApiDelegationOutput>> BatchCreateMaskinportenScopeDelegation(string party, ApiDelegationInput delegation)
{
List<ApiDelegationOutput> delegationOutputs = new List<ApiDelegationOutput>();

foreach (var org in delegation.OrgNumbers)
{
foreach (var api in delegation.ApiIdentifiers)
{
var delegationObject = new DelegationInput
{
To = new List<IdValuePair> { new IdValuePair { Id = "urn:altinn:organizationnumber", Value = org } },
Rights = new List<Right>
{
new Right
{
Resource = new List<IdValuePair> { new IdValuePair { Id = "urn:altinn:resource", Value = api } }
}
}
};
try
{
var response = await _maskinportenSchemaClient.CreateMaskinportenScopeDelegation(party, delegationObject);
string responseContent = await response.Content.ReadAsStringAsync();

delegationOutputs.Add(new ApiDelegationOutput()
{
OrgNumber = org,
ApiId = api,
Success = response.StatusCode == System.Net.HttpStatusCode.Created
});
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine(e.Message);
delegationOutputs.Add(new ApiDelegationOutput()
{
OrgNumber = org,
ApiId = api,
Success = false,
});
}
}
}

return delegationOutputs;
}

/// <inheritdoc />
public async Task<List<DelegationResponseData>> DelegationCheck(string partyId, Right request)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,14 @@ public interface IAPIDelegationService
/// <returns></returns>
public Task<HttpResponseMessage> CreateMaskinportenScopeDelegation(string party, DelegationInput delegation);

/// <summary>
/// Delegates maskinporten scope to organizations, on behalf of a sinlge party. This endpoint enables both single delegations and batches of one or more maskinporten scopes to one or more organizations
/// </summary>
/// <param name="party">party</param>
/// <param name="delegation">delegation to be performed</param>
/// <returns></returns>
public Task<List<ApiDelegationOutput>> BatchCreateMaskinportenScopeDelegation(string party, ApiDelegationInput delegation);

/// <summary>
/// Endpoint for performing a check if the user can delegate a maskinporten schema service to a specified reportee.
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
[
{
"orgNumber": "810418362",
"apiId": "appid-402",
"success": true
},
{
"orgNumber": "123456789",
"apiId": "appid-402",
"success": true
},
{
"orgNumber": "123456789",
"apiId": "invalid_org_id",
"success": false
},
{
"orgNumber": "810418362",
"apiId": "invalid_org_id",
"success": false
}
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
[
{
"orgNumber": "810418362",
"apiId": "appid-402",
"success": true
},
{
"orgNumber": "810418362",
"apiId": "appid-400",
"success": true
},
{
"orgNumber": "810418532",
"apiId": "appid-402",
"success": true
},
{
"orgNumber": "810418532",
"apiId": "appid-400",
"success": true
}
]
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,59 @@ public async Task PostMaskinportenSchemaDelegation_ExternalExceptionHandled()
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
}


/// <summary>
/// Tests the batch delegation of Maskinporten schema resources to various organizations by an authenticated user (DAGL) for multiple reportee parties.
/// Verifies that a successful delegation returns a 200 OK status code with a response body containing the expected delegated rights for all parties.
/// </summary>
[Fact]
public async Task PostBatchMaskinportenSchemaDelegation_DAGL_Success()
{

string fromParty = "50005545";
_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", PrincipalUtil.GetToken(20000490, 50002598));

List<ApiDelegationOutput> expectedResponse = GetExpectedBatchResponse("Delegation", "batch-delegation-response");
StreamContent requestContent = GetRequestContent("Delegation", "Input_Batch");

// Act
HttpResponseMessage response = await _client.PostAsync($"accessmanagement/api/v1/apidelegation/{fromParty}/offered/batch", requestContent);
string responseContent = await response.Content.ReadAsStringAsync();

// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);

List<ApiDelegationOutput> actualResponse = JsonSerializer.Deserialize<List<ApiDelegationOutput>>(responseContent, options);
AssertionUtil.AssertEqual(expectedResponse, actualResponse);
}

/// <summary>
/// Tests the partial success of batch delegation of resources to multiple organizations by an authenticated user, where some delegations succeed while others fail.
/// Verifies that the response appropriately reflects the mixed outcome, indicating both the successfully delegated rights and the failures, along with corresponding status codes for each.
/// </summary>
[Fact]
public async Task PostBatchMaskinportenSchemaDelegation_DAGL_PartialSuccess()
{

string fromParty = "50005545";
_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", PrincipalUtil.GetToken(20000490, 50002598));

List<ApiDelegationOutput> expectedResponse = GetExpectedBatchResponse("Delegation", "batch-delegation-mixed-response");
StreamContent requestContent = GetRequestContent("Delegation", "Input_Batch_Invalid");

// Act
HttpResponseMessage response = await _client.PostAsync($"accessmanagement/api/v1/apidelegation/{fromParty}/offered/batch", requestContent);
string responseContent = await response.Content.ReadAsStringAsync();

// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);

List<ApiDelegationOutput> actualResponse = JsonSerializer.Deserialize<List<ApiDelegationOutput>>(responseContent, options);

AssertionUtil.AssertEqual(expectedResponse, actualResponse);
}


/// <summary>
/// Test case: RevokeOfferedMaskinportenScopeDelegation for the reportee party 50004222 of the nav_aa_distribution
/// maskinporten schema resource from the resource registry,
Expand Down Expand Up @@ -256,7 +309,7 @@ public async Task DelegationCheck_HasDelegableRights()
// Arrange
int reporteePartyId = 50076002;
string resourceId = "default";

string folderPath = Path.Combine(unitTestFolder, "Data", "ExpectedResults", "MaskinportenSchema", "DelegationCheck", "scope-access-schema");
string fullPath = Path.Combine(folderPath, resourceId + ".json");
List<DelegationResponseData> expectedResponse = Util.GetMockData<List<DelegationResponseData>>(fullPath);
Expand All @@ -267,11 +320,11 @@ public async Task DelegationCheck_HasDelegableRights()

// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);

List<DelegationResponseData> actualResponse = JsonSerializer.Deserialize<List<DelegationResponseData>>(responseContent, options);
AssertionUtil.AssertCollections(expectedResponse, actualResponse, AssertionUtil.AssertEqual);
}

/// <summary>
/// Test case: Tests if response has insufficient access level
/// Expected: Resource has insufficient access level
Expand All @@ -294,7 +347,7 @@ public async Task DelegationCheck_InsufficientAccessLevel()

// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);

List<DelegationResponseData> actualResponse = JsonSerializer.Deserialize<List<DelegationResponseData>>(responseContent, options);
AssertionUtil.AssertCollections(expectedResponse, actualResponse, AssertionUtil.AssertEqual);
}
Expand All @@ -316,13 +369,28 @@ private static StreamContent GetRequestContent(string operation, string inputFil
return content;
}

private static DelegationOutput GetExpectedResponse(string operation, string resourceId)
private static DelegationOutput GetExpectedResponse(string operation, string fileName)
{
string responsePath = $"Data/MaskinportenSchema/{operation}/{resourceId}.json";
string responsePath = $"Data/MaskinportenSchema/{operation}/{fileName}.json";
string content = File.ReadAllText(responsePath);
return (DelegationOutput)JsonSerializer.Deserialize(content, typeof(DelegationOutput), new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
}

class BatchDelegationOutput
{
public List<ApiDelegationOutput> result { get; set; }
}


private static List<ApiDelegationOutput> GetExpectedBatchResponse(string operation, string resourceId)
{
string responsePath = $"Data/MaskinportenSchema/{operation}/{resourceId}.json";
string content = File.ReadAllText(responsePath);

var res = (List<ApiDelegationOutput>)JsonSerializer.Deserialize(content, typeof(List<ApiDelegationOutput>), new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
return res;
}

private static List<MaskinportenSchemaDelegationFE> GetExpectedInboundDelegationsForParty(int covererdByPartyId)
{
List<MaskinportenSchemaDelegationFE> inboundDelegations = new List<MaskinportenSchemaDelegationFE>();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"apiIdentifiers": ["appid-402", "appid-400"],
"orgNumbers": ["810418362", "810418532"]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"apiIdentifiers": ["appid-402", "invalid_org_id"],
"orgNumbers": ["810418362", "123456789"]
}
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ public static void AssertEqual(List<ContactPoint> expected, List<ContactPoint> a
Assert.Equal(expected[i].ContactPage, actual[i].ContactPage);
}
}

/// <summary>
/// Assert that two Lists of <see cref="ResourceOwnerFE" /> have the same property in the same positions.
/// </summary>
Expand Down Expand Up @@ -269,5 +269,18 @@ private static void AssertEqual(IdValuePair expected, IdValuePair actual)
Assert.Equal(expected.Id, actual.Id);
Assert.Equal(expected.Value, actual.Value);
}

public static void AssertEqual(List<ApiDelegationOutput> expected, List<ApiDelegationOutput> actual)
{
Assert.NotNull(actual);
Assert.NotNull(expected);

Assert.Equal(expected.Count, actual.Count);
foreach (var item in expected)
{
var a = actual.FindAll(c => c.OrgNumber == item.OrgNumber && c.ApiId == item.ApiId && c.Success == item.Success);
Assert.Single(a);
}
}
}
}
Loading

0 comments on commit 262626f

Please sign in to comment.