diff --git a/src/web/hooks/__tests__/useLoadCapabilities.jsx b/src/web/hooks/__tests__/useLoadCapabilities.jsx new file mode 100644 index 0000000000..8aefc0c858 --- /dev/null +++ b/src/web/hooks/__tests__/useLoadCapabilities.jsx @@ -0,0 +1,46 @@ +/* SPDX-FileCopyrightText: 2024 Greenbone AG + * + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +import {describe, test, expect, testing} from '@gsa/testing'; + +import {rendererWith, screen, wait} from 'web/utils/testing'; + +import useLoadCapabilities from '../useLoadCapabilities'; + +const TestComponent = () => { + const capabilities = useLoadCapabilities(); + return ( + <> + {capabilities && + capabilities.map(capability => { + return ( +
+ {capability.name} +
+ ); + })} + + ); +}; + +describe('useLoadCapabilities tests', () => { + test('should load capabilities', async () => { + const capabilities = [{name: 'cap_1'}, {name: 'cap_2'}]; + const response = {data: capabilities}; + const gmp = { + user: { + currentCapabilities: testing.fn(() => Promise.resolve(response)), + }, + }; + const {render} = rendererWith({gmp}); + + render(); + + await wait(); + + expect(gmp.user.currentCapabilities).toHaveBeenCalled(); + expect(screen.getAllByTestId('capability').length).toEqual(2); + }); +}); diff --git a/src/web/hooks/useLoadCapabilities.jsx b/src/web/hooks/useLoadCapabilities.jsx new file mode 100644 index 0000000000..63a5ce9ee3 --- /dev/null +++ b/src/web/hooks/useLoadCapabilities.jsx @@ -0,0 +1,45 @@ +/* SPDX-FileCopyrightText: 2024 Greenbone AG + * + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +import {useEffect, useState} from 'react'; + +import logger from 'gmp/log'; +import Capabilities from 'gmp/capabilities/capabilities'; + +import useGmp from '../utils/useGmp'; + +const log = logger.getLogger('web.useLoadCapabilities'); + +/** + * Hook to load the user's capabilities from the backend + */ +const useLoadCapabilities = () => { + const gmp = useGmp(); + const [capabilities, setCapabilities] = useState(); + + useEffect(() => { + gmp.user + .currentCapabilities() + .then(response => { + const loadedCapabilities = response.data; + log.debug('User capabilities', loadedCapabilities); + setCapabilities(loadedCapabilities); + }) + .catch(rejection => { + if (rejection.isError()) { + log.error( + 'An error occurred during fetching capabilities', + rejection, + ); + } + // use empty capabilities + setCapabilities(new Capabilities()); + }); + }, [gmp.user]); + + return capabilities; +}; + +export default useLoadCapabilities;