diff --git a/src/context/index.ts b/src/context/index.ts index a1262d0..54ba283 100644 --- a/src/context/index.ts +++ b/src/context/index.ts @@ -1,2 +1,2 @@ export { OAuth2Provider } from './auth-context'; -export { useOAuth2 } from './use-oauth2'; +export { useOAuth2Context } from './use-oauth2'; diff --git a/src/context/use-oauth2.ts b/src/context/use-oauth2.ts index 2e47dfd..48a9864 100644 --- a/src/context/use-oauth2.ts +++ b/src/context/use-oauth2.ts @@ -1,7 +1,7 @@ import { useContext } from 'react'; import { OAuth2Context } from '../context/auth-context'; -export const useOAuth2 = () => { +export const useOAuth2Context = () => { const context = useContext(OAuth2Context); if (!context) { throw new Error('useOAuth2 must be used within an OAuth2Provider'); diff --git a/src/hooks/index.ts b/src/hooks/index.ts new file mode 100644 index 0000000..e9165eb --- /dev/null +++ b/src/hooks/index.ts @@ -0,0 +1 @@ +export { useOAuth2 } from './useOAuth2'; diff --git a/src/hooks/useOAuth2.ts b/src/hooks/useOAuth2.ts new file mode 100644 index 0000000..da4db46 --- /dev/null +++ b/src/hooks/useOAuth2.ts @@ -0,0 +1,55 @@ +import { useEffect, useCallback } from 'react'; +import { getOAuthLogoutUrl, getOAuthOrigin } from '../constants/'; + +type MessageEvent = { + data: 'logout_complete' | 'logout_error'; + origin: string; +}; + +/** + * Custom hook to handle OAuth2 logout and redirection. + * + * @param {(oauthUrl: string) => Promise} WSLogoutAndRedirect - Function to handle logout and redirection. + * @returns {{ OAuth2Logout: () => Promise }} - Object containing the OAuth2Logout function. + */ +export const useOAuth2 = (WSLogoutAndRedirect: () => Promise) => { + useEffect(() => { + const onMessage = async (event: MessageEvent) => { + const allowedOrigin = getOAuthOrigin(); + if (allowedOrigin === event.origin) { + if (event.data === 'logout_complete') { + WSLogoutAndRedirect(); + } else { + console.warn('Unexpected message received: ', event.data); + } + } else { + console.warn('Unexpected postmessage origin: ', event.origin); + } + }; + + window.addEventListener('message', onMessage); + return () => window.removeEventListener('message', onMessage); + }, [WSLogoutAndRedirect]); + + const OAuth2Logout = useCallback(async () => { + let iframe: HTMLIFrameElement | null = document.getElementById('logout-iframe') as HTMLIFrameElement; + if (!iframe) { + iframe = document.createElement('iframe'); + iframe.id = 'logout-iframe'; + iframe.style.display = 'none'; + document.body.appendChild(iframe); + + setTimeout(() => { + WSLogoutAndRedirect(); + }, 10000); + } + + iframe.src = getOAuthLogoutUrl(); + + iframe.onerror = error => { + console.error('There has been a problem with the logout: ', error); + }; + }, [WSLogoutAndRedirect]); + + return { OAuth2Logout }; +}; diff --git a/src/index.ts b/src/index.ts index fc55358..a9d057b 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1 +1,2 @@ export * from './context/'; +export * from './hooks/';