Skip to content

Commit

Permalink
fixed bug (#724)
Browse files Browse the repository at this point in the history
  • Loading branch information
allinox authored Feb 12, 2024
1 parent 27c97ff commit 5368390
Show file tree
Hide file tree
Showing 13 changed files with 74 additions and 43 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ public interface ISingleRightClient
/// <param name="request">
/// The delegation access check request object that's going to be consumed by the backend
/// </param>
/// <returns>List<DelegationAccessCheckResponse /></returns>
Task<List<DelegationResponseData>> CheckDelegationAccess(string partyId, Right request);
/// <returns>HttpResponseMessage: The response from backend /></returns>
Task<HttpResponseMessage> CheckDelegationAccess(string partyId, Right request);

/// <summary>
/// Creates a single rights delegation
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public interface ISingleRightService
/// </param>
/// <param name="request">The delegation access check request object that's going to be consumed by the backend</param>
/// <returns> List<DelegationAccessCheckResponse /></returns>
Task<List<DelegationResponseData>> CheckDelegationAccess(string partyId, Right request);
Task<HttpResponseMessage> CheckDelegationAccess(string partyId, Right request);

/// <summary>
/// Creates a single right delegation from a given party
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public SingleRightService(ISingleRightClient singleRightClient)
}

/// <inheritdoc />
public async Task<List<DelegationResponseData>> CheckDelegationAccess(string partyId, Right request)
public async Task<HttpResponseMessage> CheckDelegationAccess(string partyId, Right request)
{
return await _singleRightClient.CheckDelegationAccess(partyId, request);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public SingleRightClient(
}

/// <inheritdoc />
public async Task<List<DelegationResponseData>> CheckDelegationAccess(string partyId, Right request)
public async Task<HttpResponseMessage> CheckDelegationAccess(string partyId, Right request)
{
try
{
Expand All @@ -54,18 +54,7 @@ public async Task<List<DelegationResponseData>> CheckDelegationAccess(string par
StringContent requestBody = new StringContent(JsonSerializer.Serialize(request, _serializerOptions), Encoding.UTF8, "application/json");
HttpResponseMessage response = await _client.PostAsync(token, endpointUrl, requestBody);

if (response.StatusCode == HttpStatusCode.OK)
{
string responseContent = await response.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<List<DelegationResponseData>>(responseContent, _serializerOptions);
}
else
{
string responseContent = await response.Content.ReadAsStringAsync();
HttpStatusException error = JsonSerializer.Deserialize<HttpStatusException>(responseContent, _serializerOptions);

throw error;
}
return response;
}
catch (Exception ex)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,32 +19,21 @@ public SingleRightClientMock()
}

/// <inheritdoc />
public Task<List<DelegationResponseData>> CheckDelegationAccess(string partyId, Right request)
public async Task<HttpResponseMessage> CheckDelegationAccess(string partyId, Right request)
{
string resourceFileName = GetMockDataFilename(request.Resource);
string path = Path.Combine(localPath, "Data", "SingleRight", "DelegationAccessCheckResponse", resourceFileName+".json");
string path = Path.Combine(localPath, "Data", "SingleRight", "DelegationAccessCheckResponse");

List<DelegationResponseData> expectedResponse = Util.GetMockData<List<DelegationResponseData>>(path);

return Task.FromResult(expectedResponse);
return await GetMockedHttpResponse(path, resourceFileName);
}

/// <inheritdoc />
public async Task<HttpResponseMessage> CreateDelegation(string party, DelegationInput delegation)
{
string resourceFileName = GetMockDataFilename(delegation.Rights.First().Resource);
string dataPath = Path.Combine(localPath, "Data", "SingleRight", "CreateDelegation");

try
{
string data = Util.GetMockDataSerialized(dataPath, resourceFileName + ".json");
return new HttpResponseMessage
{ StatusCode = HttpStatusCode.OK, Content = new StringContent(data) };
}
catch
{
return new HttpResponseMessage(HttpStatusCode.BadRequest);
}

return await GetMockedHttpResponse(dataPath, resourceFileName);
}

private static string GetMockDataFilename(List<IdValuePair> resourceReference)
Expand All @@ -64,5 +53,19 @@ private static string GetMockDataFilename(List<IdValuePair> resourceReference)
return "Unknown";
}
}

private static async Task<HttpResponseMessage> GetMockedHttpResponse(string path, string resourceFileName)
{
try
{
string data = Util.GetMockDataSerialized(path, resourceFileName + ".json");
return new HttpResponseMessage
{ StatusCode = HttpStatusCode.OK, Content = new StringContent(data) };
}
catch
{
return new HttpResponseMessage(HttpStatusCode.BadRequest);
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,28 @@ public async Task<ActionResult<List<DelegationResponseData>>> CheckDelegationAcc
{
try
{
return await _singleRightService.CheckDelegationAccess(partyId, request);
HttpResponseMessage response = await _singleRightService.CheckDelegationAccess(partyId, request);

if (response.StatusCode == HttpStatusCode.OK)
{
string responseContent = await response.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<List<DelegationResponseData>>(responseContent, _serializerOptions);
}

if (response.StatusCode == HttpStatusCode.BadRequest || response.StatusCode == HttpStatusCode.Unauthorized)
{
string responseContent = await response.Content.ReadAsStringAsync();
return new ObjectResult(ProblemDetailsFactory.CreateProblemDetails(HttpContext, (int?)response.StatusCode, response.StatusCode == HttpStatusCode.BadRequest ? "Bad request" : "Unauthorized from backend", detail: responseContent));
}
else
{
string responseContent = await response.Content.ReadAsStringAsync();
return new ObjectResult(ProblemDetailsFactory.CreateProblemDetails(HttpContext, (int?)response.StatusCode, "Unexpected HttpStatus response", detail: responseContent));
}
}
catch (Exception)
catch (Exception ex)
{
_logger.LogError(ex, "Unexpected exception occurred during delegation of resource:" + ex.Message);
return new ObjectResult(ProblemDetailsFactory.CreateProblemDetails(HttpContext));
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,9 @@ export const ResourceActionBar = ({

useUpdate(() => {
if (
(status === ServiceStatus.NotDelegable || status === ServiceStatus.HTTPError) &&
(status === ServiceStatus.NotDelegable ||
status === ServiceStatus.HTTPError ||
status === ServiceStatus.Unauthorized) &&
previousStatus !== undefined
) {
setOpen(true);
Expand All @@ -65,6 +67,7 @@ export const ResourceActionBar = ({
return 'success';
case ServiceStatus.NotDelegable:
case ServiceStatus.HTTPError:
case ServiceStatus.Unauthorized:
return 'danger';
default:
return 'neutral';
Expand Down Expand Up @@ -135,6 +138,7 @@ export const ResourceActionBar = ({
case ServiceStatus.PartiallyDelegable:
return undoButton;
case ServiceStatus.NotDelegable:
case ServiceStatus.Unauthorized:
return notDelegableLabel;
default:
return addButton;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,7 @@ export const SearchSection = ({ onAdd, onUndo }: SearchSectionParams) => {

const errorCodeTextKeyList =
currentServiceWithStatus?.status === ServiceStatus.NotDelegable ||
currentServiceWithStatus?.status === ServiceStatus.Unauthorized ||
currentServiceWithStatus?.status === ServiceStatus.HTTPError
? currentServiceWithStatus.rightList?.flatMap(
(result) => result.details?.map((detail) => detail.code) || [],
Expand Down Expand Up @@ -220,9 +221,10 @@ export const SearchSection = ({ onAdd, onUndo }: SearchSectionParams) => {
you: t('common.you_uppercase'),
})}
</Paragraph>
{prioritizedErrorCodes[0] !== ServiceStatus.HTTPError && (
<Paragraph>{t('single_rights.ceo_or_main_admin_can_help')}</Paragraph>
)}
{prioritizedErrorCodes[0] !== ServiceStatus.HTTPError &&
prioritizedErrorCodes[0] !== ServiceStatus.Unauthorized && (
<Paragraph>{t('single_rights.ceo_or_main_admin_can_help')}</Paragraph>
)}
</Alert>
)}
<Paragraph size='small'>{resource.description}</Paragraph>
Expand Down
2 changes: 2 additions & 0 deletions src/localizations/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,8 @@
"new_error_title": "New error",
"generic_error_try_again_title": "Whoops, we stumbled on a technical error",
"generic_error_try_again": "Try adding the service again by clicking on the plus sign again. Contact Altinn Servicedesk if the problem persists.",
"unauthorized_for_party_title": "Manglar delegasjonstilgang",
"unauthorized_for_party": "Du kan ikkje delegere tenester for valde aktør. Om du meinte å delegere på vegner av nokon andre, vennlegst gå til profilen og vel denne aktøren frå avgjevarlista.",
"give_more_rights": "Give more rights",
"has_received_these_rights": "{{name}} has received these rights:",
"rights_are_valid_until_deletion": "The rights are valid until they're deleted or withdrawn",
Expand Down
2 changes: 2 additions & 0 deletions src/localizations/no_nb.json
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,8 @@
"new_error_title": "Ny feil",
"generic_error_try_again_title": "Oj, det oppstod en teknisk feil",
"generic_error_try_again": "Prøv å legge til tjenesten på nytt ved å klikke på pluss-tegnet igjen. Ta kontakt med Altinn Servicedesk hvis problemet fortsetter.",
"unauthorized_for_party_title": "Mangler delegeringstilgang",
"unauthorized_for_party": "Du kan ikke delegere tjenester for valgte aktør. Dersom du mente å delegere på vegne av noen andre, vennligst gå til profilen og velg denne aktøren fra avgiverlisten.",
"missing_delegable_right": "Mangler rettighet",
"missing_srr_right_access_title": "Mangler SRR-rettighet",
"confirm_delegation_text": "Bekreft at du vil gi disse rettighetene til {{name}}.",
Expand Down
2 changes: 2 additions & 0 deletions src/localizations/no_nn.json
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,8 @@
"new_error_title": "Ny feil",
"generic_error_try_again_title": "Oj, det oppstod ein teknisk feil",
"generic_error_try_again": "Prøv å legge til tenesta på nytt ved å klikke på pluss-teiknet igjen. Ta kontakt med Altinn Servicedesk om problemet held fram.",
"unauthorized_for_party_title": "Manglar delegasjonstilgang",
"unauthorized_for_party": "Du kan ikkje delegere tenester for valde aktør. Om du meinte å delegere på vegner av nokon andre, vennlegst gå til profilen og vel denne aktøren frå avgjevarlista.",
"missing_delegable_right": "Manglar rett",
"missing_srr_right_access_title": "Manglar SRR-rettegheit",
"complete_delegation": "Fullfør delegering",
Expand Down
4 changes: 4 additions & 0 deletions src/resources/utils/errorCodeUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ export enum ErrorCode {
MissingDelegationAccess = 'MissingDelegationAccess',
MissingSrrRightAccess = 'MissingSrrRightAccess',
HTTPError = 'HTTPError',
Unauthorized = 'Unauthorized',
InsufficientAuthenticationLevel = 'InsufficientAuthenticationLevel',
Unknown = 'Unknown',
}
Expand All @@ -19,6 +20,8 @@ export const getErrorCodeTextKey = (errorCode: string | undefined): string | und
return 'single_rights.unknown';
case ErrorCode.HTTPError:
return 'single_rights.generic_error_try_again';
case ErrorCode.Unauthorized:
return 'single_rights.unauthorized_for_party';
case ErrorCode.InsufficientAuthenticationLevel:
return 'api_delegation.insufficient_authentication_level';
case undefined:
Expand All @@ -30,6 +33,7 @@ export const getErrorCodeTextKey = (errorCode: string | undefined): string | und

export const prioritizeErrors = (errors: string[]): string[] => {
const priorityOrder: string[] = [
ErrorCode.Unauthorized,
ErrorCode.HTTPError,
ErrorCode.MissingRoleAccess,
ErrorCode.MissingDelegationAccess,
Expand Down
13 changes: 9 additions & 4 deletions src/rtk/features/singleRights/singleRightsSlice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ export enum ServiceStatus {
PartiallyDelegable = 'PartiallyDelegable',
Unchecked = 'Unchecked',
HTTPError = 'HTTPError',
Unauthorized = `Unauthorized`,
}

export interface DelegationAccessCheckDto {
Expand Down Expand Up @@ -265,17 +266,21 @@ const singleRightSlice = createSlice({

.addCase(delegationAccessCheck.rejected, (state, action) => {
const serviceID = action.meta.arg.serviceResource.identifier;
const errorCode =
action.payload.response.status === 401
? ServiceStatus.Unauthorized
: ServiceStatus.HTTPError;

const nextStateArray = state.servicesWithStatus.map((sws: ServiceWithStatus) => {
if (sws.service?.identifier === serviceID) {
const delegationResponseList: Right[] = [
{
resource: [{ id: serviceID }],
resource: action.meta.arg.resourceReference,
action: '',
status: ServiceStatus.HTTPError,
status: errorCode,
details: [
{
code: ServiceStatus.HTTPError,
code: errorCode,
},
],
},
Expand All @@ -284,7 +289,7 @@ const singleRightSlice = createSlice({
sws.service.identifier = serviceID;
sws.rightList = delegationResponseList;
sws.isLoading = false;
sws.status = ServiceStatus.HTTPError;
sws.status = errorCode;
}
return sws;
});
Expand Down

0 comments on commit 5368390

Please sign in to comment.