Skip to content

Commit

Permalink
Error handling for GetRolesForUser
Browse files Browse the repository at this point in the history
  • Loading branch information
sonwit committed Jan 17, 2025
1 parent 91f514b commit 1ec9fb1
Show file tree
Hide file tree
Showing 5 changed files with 78 additions and 13 deletions.
30 changes: 29 additions & 1 deletion .mock/handlers/accessPackage.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,35 @@
import { http, HttpResponse } from 'msw';

export const accessPackageHandlers = (ACCESSMANAGEMENT_BASE_URL: string) => [
http.get(ACCESSMANAGEMENT_BASE_URL + '/accesspackage/search', () => {
http.get(`${ACCESSMANAGEMENT_BASE_URL}/role/assignments/:ownerId/:holderId`, () => {
HttpResponse.json([
{
id: '461b0ec2-6795-4055-9306-2acefd7c6a31 ',
roleId: 'de42ae15-c265-42b3-8060-64c779684902',
fromId: 'cd35779b-b174-4ecc-bbef-ece13611be7f',
toId: '167536b5-f8ed-4c5a-8f48-0279507e53ae',
role: {
id: 'de42ae15-c265-42b3-8060-64c779684902',
name: 'Styremedlem',
code: 'MEDL',
description: 'Fysisk- eller juridisk person som inngår i et styre',
},
},
{
id: '43f42152-8900-4fcf-ac70-62d2d566581c',
roleId: 'de42ae15-c265-42b3-8060-64c779684902',
fromId: 'cd35779b-b174-4ecc-bbef-ece13611be7f',
toId: '167536b5-f8ed-4c5a-8f48-0279507e53ae',
role: {
id: '72c336a2-1705-4aef-b220-7f4aa6c0e69d',
name: 'Styrets leder',
code: 'LEDE',
description: 'Fysisk- eller juridisk person som er styremedlem og leder et styre',
},
},
]);
}),
http.get(`${ACCESSMANAGEMENT_BASE_URL}/accesspackage/search`, () => {
return HttpResponse.json([
{
id: '589217CF-6070-474F-9989-8C5359C740F4',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,10 @@ public Task<List<AccessPackage>> GetAccessPackageSearchMatches(string languageCo
/// <inheritdoc />
public Task<List<RoleAssignment>> GetRolesForUser(string languageCode, Guid rightOwnerUuid, Guid rightHolderUuid)
{
if (rightHolderUuid == Guid.Empty)
{
throw new Exception("Right holder uuid is not valid");
}
try {
List<RoleAssignment> allAssignments = Util.GetMockData<List<RoleAssignment>>($"{dataFolder}/Roles/GetRolesForUser/{rightHolderUuid}.json");
if (allAssignments == null)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using Altinn.AccessManagement.UI.Core.Models.Role;
using Altinn.AccessManagement.UI.Mocks.Utils;
using Altinn.AccessManagement.UI.Tests.Utils;
using Microsoft.AspNetCore.Mvc.ModelBinding;

namespace Altinn.AccessManagement.UI.Tests.Controllers
{
Expand Down Expand Up @@ -78,5 +79,22 @@ public async Task GetRolesForUser_HasNoRoles()
AssertionUtil.AssertCollections(expectedResult, actualResult, AssertionUtil.AssertEqual);

}

/// <summary>
/// Test case: Get roles for user that doesn't has roles
/// Expected: Returns users roles for the given and right holder and right owner
/// </summary>
[Fact]
public async Task GetRolesForUser_InternalError()
{
string rightOwnerUuid = "cd35779b-b174-4ecc-bbef-ece13611be7f"; // Valid reportee
string rightHolderUuid = "00000000-0000-0000-0000-000000000000"; // invalid uuid that will cause internal error

// Act
HttpResponseMessage response = await _client.GetAsync($"accessmanagement/api/v1/role/assignments/{rightOwnerUuid}/{rightHolderUuid}");

// Assert
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
using Microsoft.AspNetCore.Mvc;

namespace Altinn.AccessManagement.UI.Controllers
{
/// <summary>
/// Base controller class providing common functionality for derived controllers.
/// </summary>
public abstract class BaseController : ControllerBase
{
/// <summary>
/// Validates the model state and returns a BadRequest result if the model state is invalid.
/// </summary>
/// <returns>A BadRequest result if the model state is invalid; otherwise, null.</returns>
protected ActionResult ValidateModelState()
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}

Check failure on line 19 in backend/src/Altinn.AccessManagement.UI/Altinn.AccessManagement.UI/Controllers/BaseController.cs

View workflow job for this annotation

GitHub Actions / Continous Integration / Build

Check failure on line 19 in backend/src/Altinn.AccessManagement.UI/Altinn.AccessManagement.UI/Controllers/BaseController.cs

View workflow job for this annotation

GitHub Actions / Continous Integration / Build

Check warning on line 19 in backend/src/Altinn.AccessManagement.UI/Altinn.AccessManagement.UI/Controllers/BaseController.cs

View workflow job for this annotation

GitHub Actions / Continous Integration / Test

return null;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,8 @@ namespace Altinn.AccessManagement.UI.Controllers
/// The <see cref="RoleController"/> provides the API endpoints related to roles.
/// </summary>
[Route("accessmanagement/api/v1/role")]
public class RoleController : Controller
public class RoleController : BaseController
{
private readonly IAccessPackageService _accessPackageService;
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly ILogger _logger;
private readonly JsonSerializerOptions _serializerOptions = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
Expand All @@ -25,9 +24,8 @@ public class RoleController : Controller
/// <summary>
/// Initializes a new instance of the <see cref="RoleController"/> class
/// </summary>
public RoleController(IAccessPackageService accessPackageService, IHttpContextAccessor httpContextAccessor, ILogger<RoleController> logger, IRoleService roleService)
public RoleController(IHttpContextAccessor httpContextAccessor, ILogger<RoleController> logger, IRoleService roleService)
{
_accessPackageService = accessPackageService;
_httpContextAccessor = httpContextAccessor;
_logger = logger;
_roleService = roleService;
Expand All @@ -43,16 +41,10 @@ public RoleController(IAccessPackageService accessPackageService, IHttpContextAc
[Route("assignments/{rightOwnerUuid}/{rightHolderUuid}")]
public async Task<ActionResult<List<RoleAssignment>>> GetRolesForUser(Guid rightOwnerUuid, Guid rightHolderUuid)

Check failure

Code scanning / SonarCloud

ModelState.IsValid should be called in controller actions High

ModelState.IsValid should be checked in controller actions. See more on SonarQube Cloud
{
var httpContext = _httpContextAccessor.HttpContext;
if (httpContext == null)
{
_logger.LogError("HttpContext is null");
return StatusCode(StatusCodes.Status500InternalServerError, "Internal server error");
}

var languageCode = LanguageHelper.GetSelectedLanguageCookieValueBackendStandard(httpContext);
try
{
var httpContext = _httpContextAccessor.HttpContext;
var languageCode = LanguageHelper.GetSelectedLanguageCookieValueBackendStandard(httpContext);
return await _roleService.GetRolesForUser(languageCode, rightOwnerUuid, rightHolderUuid);
}
catch (HttpStatusException ex)
Expand Down

0 comments on commit 1ec9fb1

Please sign in to comment.