Skip to content

Commit

Permalink
Add cypress test
Browse files Browse the repository at this point in the history
  • Loading branch information
louptheron committed Oct 16, 2024
1 parent c1cacd2 commit d2c3206
Show file tree
Hide file tree
Showing 6 changed files with 47 additions and 23 deletions.
17 changes: 17 additions & 0 deletions frontend/cypress/e2e/authorization/authorization.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/* eslint-disable no-undef */

context('Authorization', () => {
beforeEach(() => {
cy.loadPath('/#@-824534.42,6082993.21,8.70')
})

it('Should redirect to login page if an API request is Unauthorized', () => {
// When
cy.intercept('GET', `/bff/v1/vessels/search*`, { statusCode: 401 }).as('searchVessel')
cy.get('*[data-cy^="vessel-search-input"]', { timeout: 10000 }).type('Pheno')
cy.wait('@searchVessel')

// Then
cy.location('pathname').should('eq', '/login')
})
})
40 changes: 27 additions & 13 deletions frontend/src/api/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { FrontendApiError } from '@libs/FrontendApiError'
import { createApi, fetchBaseQuery, retry } from '@reduxjs/toolkit/query/react'
import { setMeasurement, startSpan } from '@sentry/react'
import { sha256 } from '@utils/sha256'
import ky from 'ky'
import ky, { HTTPError } from 'ky'

import { RTK_MAX_RETRIES, RtkCacheTagType } from './constants'
import { getOIDCConfig } from '../auth/getOIDCConfig'
Expand Down Expand Up @@ -193,22 +193,36 @@ export const monitorfishPublicApi = createApi({

export const monitorfishApiKy = ky.extend({
hooks: {
afterResponse: [
async (request, _, response) => {
if (!response.ok) {
const error: CustomResponseError = {
path: response.url,
requestData: await request.json(),
responseData: await response.json(),
status: response.status
}
beforeError: [
async error => {
const { request, response } = error

let requestData
try {
requestData = await request.json()
} catch (e) {
// eslint-disable-next-line no-console
console.error('Could not parse request data', error)
}

redirectToLoginIfUnauthorized(error)
let responseData
try {
responseData = await response.json()
} catch (e) {
// eslint-disable-next-line no-console
console.error('Could not parse response data', error)
}

throw new FrontendApiError(error.status.toString(), error)
const customError: CustomResponseError = {
path: response.url,
requestData,
responseData,
status: response.status
}
redirectToLoginIfUnauthorized(customError)

return response
// `beforeError` hook expect an HTTPError, so we fake it with `as unknown as HTTPError`
return new FrontendApiError(customError.status.toString(), customError) as unknown as HTTPError
}
],
beforeRequest: [
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/api/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,6 @@ export type RTKBaseQueryArgs =
export interface CustomResponseError {
path: string
requestData: AnyObject | undefined
responseData: BackendApi.ResponseBodyError
responseData: BackendApi.ResponseBodyError | undefined
status: number | 'FETCH_ERROR' | 'PARSING_ERROR' | 'TIMEOUT_ERROR' | 'CUSTOM_ERROR'
}
7 changes: 0 additions & 7 deletions frontend/src/auth/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,13 @@ import { HttpStatusCode } from '@api/constants'

import { paths } from '../paths'
import { router } from '../router'
import { getOIDCConfig } from './getOIDCConfig'

import type { CustomResponseError } from '@api/types'

/**
* Redirect to Login page if any HTTP request in Unauthorized
* @param error
*/
export function redirectToLoginIfUnauthorized(error: CustomResponseError) {
const { IS_OIDC_ENABLED } = getOIDCConfig()
if (!IS_OIDC_ENABLED) {
return
}

if (!error.path.includes(paths.backendForFrontend) || error.status !== HttpStatusCode.UNAUTHORIZED) {
return
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ export const monitorenvControlUnitResourceApi = monitorenvApi.injectEndpoints({
url: `/v1/control_unit_resources/${controlUnitResourceId}`
}),
transformErrorResponse: response => {
if (response.responseData.type === BackendApi.ErrorCode.FOREIGN_KEY_CONSTRAINT) {
if (response.responseData?.type === BackendApi.ErrorCode.FOREIGN_KEY_CONSTRAINT) {
return new UsageError(IMPOSSIBLE_CONTROL_UNIT_RESOURCE_DELETION_ERROR_MESSAGE)
}

Expand Down
2 changes: 1 addition & 1 deletion frontend/src/features/Mission/monitorenvMissionApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ export const monitorenvMissionApi = monitorenvApi.injectEndpoints({
url: `/v2/missions/${id}?source=${Mission.MissionSource.MONITORFISH}`
}),
transformErrorResponse: response => {
if (response.responseData.code === BackendApi.ErrorCode.EXISTING_MISSION_ACTION) {
if (response.responseData?.code === BackendApi.ErrorCode.EXISTING_MISSION_ACTION) {
return new UsageError(IMPOSSIBLE_MISSION_DELETION_ERROR_MESSAGE)
}

Expand Down

0 comments on commit d2c3206

Please sign in to comment.